Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

javascript - jQuery 1.4.4+ AJAX request - post empty array or object becomes string

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);
?>

RESPONSE:

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"
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

try applying JSON.stringify to the parameters passed

 data: JSON.stringify ( obj ),

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

quoting : Why jQuery ajax does not serialize my object?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...