我正在尝试将数组从javascript传递给PHP。 错误消息显示:
NULL警告: 为foreach()提供的参数无效 第10行的/Library/WebServer/Documents/jsontest/json_receive.php
我的代码有什么问题吗?
<script>
function sendData(){
var arr= [{
"city" : "Brussels",
"age" : 25
},
{
"city" : "Antwerp",
"age" : 40
}];
$.ajax({
type: "POST",
url: "json_receive.php",
datatype: 'JSON',
data: {arr: JSON.stringify(arr)},
success: function(data){
console.log("success:",data);
},
failure: function(errMsg) {
console.error("error:",errMsg);
}
});
}
<?php
$data = json_decode($_POST["arr"]);
// will echo the JSON.stringified - string:
echo $_POST["arr"];
// will echo the json_decode'd object
var_dump($data);
//traversing the whole object and accessing properties:
print_r($data);
foreach($data as $cityObject){
echo "City: " . $cityObject->city . ", Age: " . $cityObject->age . "<br/>";
}
?>
答案 0 :(得分:0)
正如我在评论中所说,你的代码看起来好而正常(我已经测试过了),问题是你期待的东西是在页面上打印,但Ajax
success
功能仅使用控制台。
success: function(data){
console.log("success:",data);
}