简体   繁体   中英

passing structured data to php via post

Suppose I have the following data:

var arr = [], arr1 = [], arr2 = [], arr3 = [], arr4 = [];
var a = 'something', b = 'else';
arr1['key1-1'] = 'value1-2';
arr1['key1-2'] = 'value1-2';
for (var i = 0; i < someCond; i++) {
    arr = [];
    arr['key2-1'] = 'value2-1';
    arr['key2-2'] = 'value2-2';
    arr2.push(arr);
}

Now I need to pass the hole of it to a php script.

I packaged it into a single variable like so:

var postVar = {
    a: a,
    b: b,
    arr1: arr1,
    arr2: arr2
};

I'm using jQuery so I tried to post it like this:
1)

//Works fine for a and b, not for the arrays
$.post('ajax.php', postVar, function(response){});

and this:
2)

var postVar = JSON.stringify(postVar);
$.post('ajax.php', {json: postVar}, function(response){});

with the php file

$req = json_decode(stripslashes($_POST['json']), true);

which also doesn't work.

How should I structure/format my data as to send it to PHP?

Thanks

EDIT:
Case 1: console.log(postVar); 执行console.log(postVar)

PHP print_r($_POST) response: Array ( [a] => something [b] => else )

As you can see, there are no arrays (objects) on the php side.

Case 2:
When I add the following:

postVar = JSON.stringify(postVar);
    console.log(postVar);

I get
{"a":"something","b":"else","arr1":[],"arr2":[[],[],[]]}
with console.log(postVar)

So that seems to be the problem in this case... right?

You should check for magic_quotes before add stripslashes like that

if( get_magic_quotes_gpc() ) {
    $jsonString = stripslashes( $jsonString );
}
$data = json_decode( $jsonString );

i suggest that you should turn off magic quotes... it's not magic at all

As it turns out, although Arrays are Objects, JSON.stringify ignores non Array properties on Arrays. So I had to explicitly declare all variables as objects. Except for arr2 that is really used as an array.

Here goes the full code:

var arr = {}, arr1 = {}, arr2 = [];
var a = 'something', b = 'else';
arr1['key1-1'] = 'value1-2';
arr1['key1-2'] = 'value1-2';
for (var i = 0; i < 3; i++) {
    arr = {};
    arr['key2-1'] = 'value2-1';
    arr['key2-2'] = 'value2-2';
    arr2.push(arr);
}

var postVar = {
    a: a,
    b: b,
    arr1: arr1,
    arr2: arr2
};


postVar = JSON.stringify(postVar);
$.post('ajax.php', {json: postVar}, function(response){});

And on the PHP side:

$req = json_decode($_POST['json'], true);
print_r($req);


Hope this helps others with the same problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM