Con questo PHP:
function handlePost() {
$a = $_POST['favArray'];
var_dump($a);
}
..e questa Javascript:
function post() {
var a1 = [
{"Item":"109249383",
"Desc":"item1desc",
"Remarks":"item1note"},
{"Item":"298298210",
"Desc":"item2desc",
"Remarks":"item2note"}
];
$.ajax({
type: "POST",
url: "readArray.php",
data: { favArray : a1 },
success: function() {
alert1('ok, sent');
}
});
}
... ottengo questo output:
HTTP/1.1 200 OK
Content-Type: text/html
Server: Microsoft-IIS/7.5
X-Powered-By: PHP/5.3.10
Date: Wed, 11 Jul 2012 21:04:16 GMT
Content-Length: 315
array(2) {
[0]=>
array(3) {
["Item"]=>
string(9) "109249383"
["Desc"]=>
string(9) "item1desc"
["Remarks"]=>
string(9) "item1note"
}
[1]=>
array(3) {
["Item"]=>
string(9) "298298210"
["Desc"]=>
string(9) "item2desc"
["Remarks"]=>
string(9) "item2note"
}
}
In questo caso, la codifica dei dati sul cavo è non JSON. È 'application/x-www-form-urlencoded' come predefinito utilizzato dalla funzione ajax
di jQuery. Sembra che questo:
favArray=%5B%7B%22Item%22%3A%22109249383%22%2C%22Desc%22%3A%22item1desc%22%2C
%22Remarks%22%3A%22item1note%22%7D%2C%7B%22Item%22%3A%22298298210%22%2C%22
Desc%22%3A%22item2desc%22%2C%22Remarks%22%3A%22item2note%22%7D%5D
(tutto su una riga)
Perciò non ha senso chiamare json_decode
all'interno di PHP - non c'è mai stato alcun JSON coinvolti. PHP decodifica automaticamente il corpo del post con codifica url.
Se si desidera codificare con JSON, quindi è possibile utilizzare JSON.stringify()
direttamente. Questo può richiedere json2.js
dal lato del browser. (Vedi this answer)
Per utilizzare JSON, allora si avrebbe bisogno di qualcosa di simile nel browser:
function post_json_encoded() {
$.ajax({
type: "POST",
url: "postArray.php",
contentType: 'application/json', // outbound header
dataType: 'text', // expected response
data: JSON.stringify(a1), // explicitly encode
success: function() {
alert1('ok, json sent');
}
});
}
... e poi qualcosa di simile sul lato php:
function handlePost() {
header('Content-Type: text/plain; charset="UTF-8"');
$post_body = file_get_contents('php://input');
$a = json_decode($post_body);
var_dump($a);
}
in questo caso la rappresentazione on-the-wire si presenta così:
[{"Item":"109249383","Desc":"item1desc","Remarks":"item1note"},
{"Item":"298298210","Desc":"item2desc","Remarks":"item2note"}]
...e l'uscita php var_dump è questo:
array(2) {
[0]=>
object(stdClass)#1 (3) {
["Item"]=>
string(9) "109249383"
["Desc"]=>
string(9) "item1desc"
["Remarks"]=>
string(9) "item1note"
}
[1]=>
object(stdClass)#2 (3) {
["Item"]=>
string(9) "298298210"
["Desc"]=>
string(9) "item2desc"
["Remarks"]=>
string(9) "item2note"
}
}
Prova 'var_dump ($ Farray)' per assicurarsi che sia in fase di popolato correttamente – andrewsi