array(-6ren">
gpt4 book ai didi

javascript - 在ajax中从json中选择特定的键值

转载 作者:行者123 更新时间:2023-11-28 13:05:32 24 4
gpt4 key购买 nike

我的 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");
})
});

最佳答案

尝试将 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);
<p id="output"></p>

关于javascript - 在ajax中从json中选择特定的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46758862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com