jQuery 1.4.4+ AJAX请求 - 发布空数组或对象变为字符串

时间:2011-03-15 23:02:19

标签: javascript jquery ajax json post

我在Javascript中有一个对象,我正在尝试将AJAX POST发送到PHP脚本。一切都在jQuery 1.4.1中工作,但现在在1.4.4或更高版本中,所有空数组或空对象都以字符串(0)的形式到达,这是不正确的。

JS:

$(document).ready(function() {
var obj = {};
obj.one = [];
obj.two = {};
obj.three = [];
obj.three.push('one');
obj.three.push('two');
obj.three.push('three');
obj.four = "onetwothree";

$.ajax({
    type: 'POST',
    url: 'ajax.php',
    data: obj,
    success: function(data) {
        alert(data);
    },
});
});

PHP:

<?php
var_dump($_POST);
?>

响应:

array(4) {
  ["one"]=> string(0) ""
  ["two"]=> string(0) ""
  ["three"]=> array(3) {
    [0]=> string(3) "one"
    [1]=> string(3) "two"
    [2]=> string(5) "three"
  }
  ["four"]=> string(11) "onetwothree"
}

在版本1.4.1中,它不会发送[“one”]或[“two”],但现在在较新的版本中,它作为字符串到达​​的事实会抛出整个应用程序。我有什么办法可以让空数组([])作为空数组([])到达PHP并与JavaScript对象相同吗?

2 个答案:

答案 0 :(得分:3)

尝试将JSON.stringify应用于传递的参数

 data: JSON.stringify ( obj ),

请注意,您可能希望包含contentType: "application/json"选项以提示服务器端正确处理数据。

引用:Why jQuery ajax does not serialize my object?

  

传统:true是完全错误的,因为它永远不能处理对象层次结构。你得到的是:...&amp; key = [object Object],这是所有对象的javascript toString()默认结果。

答案 1 :(得分:2)

尝试将traditional选项设置为true

$.ajax({
    type: 'POST',
    traditional: true,
    url: 'ajax.php',
    data: obj,
    success: function(data) {
        alert(data);
    }
});

查看newer APIdatatraditional选项。

如果你想在IE7中运行,可以在success回调之后删除额外的逗号。

相关问题