使用这个 PHP:
function handlePost() {
$a = $_POST['favArray'];
var_dump($a);
}
..还有这个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');
}
});
}
...我得到这个输出:
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"
}
}
在这种情况下,线路上数据的编码不是 JSON。它是 'application/x-www-form-urlencoded' 根据 jQueryajax
函数使用的默认值。看起来像这样:
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
(全部在一行上)
因此json_decode
在 PHP 中调用是没有意义的 - 从来没有涉及任何 JSON。PHP 自动解码 url 编码的帖子正文。
如果你想用 JSON 编码,那么你可以JSON.stringify()
直接使用。这可能需要json2.js
在浏览器端。(见这个答案)
要使用 JSON,您需要在浏览器中使用以下内容:
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');
}
});
}
...然后在 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);
}
在这种情况下,在线表示如下所示:
[{"Item":"109249383","Desc":"item1desc","Remarks":"item1note"},
{"Item":"298298210","Desc":"item2desc","Remarks":"item2note"}]
...和 php var_dump 输出是这样的:
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"
}
}