我的test.php中有这样的代码,ajax将请求从index.php发送到此页面。在此页面中,我创建了一个数组并将其转换为json并最终返回:
<?php
$arr = array(
"status"=>200,
"result"=>array(
"winner"=>"unknown",
"options"=>array(
"1"=>"first",
"2"=>"second"
),"question"=>"are u ok?",
"answer"=>"1"
)
);
$jsonArr = json_encode($arr);
echo $jsonArr;
?>
并在index.php中我通过ajax向test.php发送请求,我收到json。我的问题是我怎样才能提醒例如来自test.php.it的接收json的问题警告未定义
$.ajax({
type:'post',
url:'test.php',
data:{},
success:(function (response) {
var x = jQuery.parseJSON(response);
alert(x."question");
})
});
答案 0 :(得分:3)
尝试将x."question"
更改为x.result["question"]
或x.result.question
。
一切都是JavaScript中的对象。您可以使用[]
(括号)表示法在JavaScript中取消引用任何对象。如果名称中没有特殊字符,则可以省略括号和字符串,然后执行object.property
。让我们创建一个例子。
let response = JSON.stringify({
status: 200,
result: {
winner: "unknown",
options: {
"1": "first",
"2": "second"
},
question: "are u ok?",
answer: 1
}
}); // Now response is almost exactly what you get from the server
console.log(response);
let x = JSON.parse(response);
console.log(x.result.question);
&#13;
<p id="output"></p>
&#13;
答案 1 :(得分:2)
尝试将x."question"
更改为x.result.question
。