【问题标题】:jQuery 1.4.4+ AJAX request - post empty array or object becomes stringjQuery 1.4.4+ AJAX 请求 - 发布空数组或对象变成字符串
【发布时间】:2011-07-16 04:50:48
【问题描述】:

我在 Javascript 中有一个对象,我正在尝试将 AJAX POST 发送到 PHP 脚本。在 jQuery 1.4.1 中一切正常,但现在在 1.4.4 或更高版本中,所有空数组或空对象都作为不正确的 string(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 对象相同?

【问题讨论】:

  • 嗨。你找到解决这个问题的方法了吗?我也对这个感兴趣。在我看到你的帖子之前,我已经发布了this

标签: javascript jquery ajax json post


【解决方案1】:

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

 data: JSON.stringify ( obj ),

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

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

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

【讨论】:

    【解决方案2】:

    尝试将traditional 选项设置为true

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

    查看newer APIdatatraditional 选项。

    如果您希望在 IE7 中正常工作,请从 success 回调后删除多余的逗号。

    【讨论】:

    • 谢谢 Karim79,我尝试将传统转换为 true,但空数组和对象仍然作为字符串 (0) 出现,但现在我的嵌套数组变成了 [object Object]。
    猜你喜欢
    • 1970-01-01
    • 2014-12-08
    • 2017-03-22
    • 2012-06-14
    • 2017-07-23
    • 2020-04-21
    • 2015-09-18
    • 1970-01-01
    • 2018-11-18
    相关资源
    最近更新 更多