jQuery的1.4.4+ AJAX请求 - 后空数组或对象变成字符串 [英] jQuery 1.4.4+ AJAX request - post empty array or object becomes string

查看:248
本文介绍了jQuery的1.4.4+ AJAX请求 - 后空数组或对象变成字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript对象,我想AJAX POST PHP脚本。一切都在1.4.4或以上的空数组或空物体曾在的jQuery 1.4.1,但现在到作为一个字符串(0),这是不正确。

I have a object in Javascript that I am trying to AJAX POST to a PHP script. Everything worked in jQuery 1.4.1 but now in 1.4.4 or above all empty arrays or empty objects arrive as a string(0) which is incorrect.

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版本中,它会只是没有发[一]或[两会],但现在的新版本,它到达一个字符串抛出了整个应用程序的事实。有什么我可以做这样一个空数组([])在PHP到达后一个空数组([]),并同JavaScript对象?

In version 1.4.1 it would just NOT send ["one"] or ["two"], but now in the newer versions, the fact that it arrives as a string throws off the whole application. Is there anything I can do so that an empty array ([]) arrives in PHP as an empty array ([]) and same with JavaScript objects?

推荐答案

尝试运用JSON.stringify来传递的参数

try applying JSON.stringify to the parameters passed

 data: JSON.stringify ( obj ),

请注意你可能要包括的contentType:应用/ JSON的选项提示服务器端正确处理数据。

Note you'll likely want to include the contentType: "application/json" option to prompt server side to process the data correctly.

报价:为什么jQuery的AJAX不序列我的对象

传统:真的是完全错误的,因为它不能处理的对象层次。你得到什么,而不是为:...&放大器;关键= [对象对象],这是对所有对象的JavaScript的toString()的默认结果

traditional: true is completely wrong, since it can never handle object hierarchies. What you get instead is: ...&key=[object Object], which is javascript's toString() default result for all objects.

这篇关于jQuery的1.4.4+ AJAX请求 - 后空数组或对象变成字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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