jQuery.ajax()省略了“empty”对象属性 [英] jQuery.ajax() omits "empty" object attributes

查看:102
本文介绍了jQuery.ajax()省略了“empty”对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JS对象:

var data_test = { foo: [], bar: [ 'baz' ] };

当我通过 jQuery.ajax()

$.ajax({
    url: "test.php",
    type: "POST",
    data: data_test
});

事实证明只有 bar 数组是已发送,而不是 foo 一个。

It turns out only the bar array is sent, and not the foo one.

证明:在 test.php 中,我只需 var_dump 编辑 $ _ REQUEST

Proof: In test.php I simply var_dumped the $_REQUEST:

array(1) {
  ["bar"]=>
  array(1) {
    [0]=>
    string(3) "baz"
  }
}

是否有可能强制jQuery也提交一个空对象属性?我需要jQuery发送 data_test 对象的精确副本,如果它省略了破坏我逻辑的空值!

Is it possible to force jQuery to also submit an empty object attribute? I need jQuery to send an EXACT copy of the data_test object, if it omits empty value that breaks my logic!

推荐答案

游戏稍晚(非常),但我想指出,如果您的应用程序已准备好接受JSON,您可以使用JSON.stringify发送空数组:

A little (very) late to the game, but I wanted to point out that if your application is ready to accept JSON, you can send empty arrays using JSON.stringify:

var data_test = { foo: [], bar: [ 'baz' ] };

$.ajax({
    url: "test.php",
    type: "POST",
    data: JSON.stringify(data_test),
    contentType: 'application/json'
});

这应该发布空数组。请注意,从IE8开始可以使用 JSON.stringify ,但您可以随时使用 json .js 填补这一空白。

This should post the empty array. Beware that JSON.stringify is available starting from IE8, but you could always use json.js to fill this gap.

这篇关于jQuery.ajax()省略了“empty”对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆