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

标签 javascript jquery json ajax

我的 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/

相关文章:

javascript - 根据数据属性用按钮执行不同的操作

javascript - 是否可以确定 IFrame 中视频的高度?

javascript - 如何迭代彼此独立的列表组

python - 使用 json 序列化时跳过未知项目

java - 将 Json 数组映射到 Java 模型

json - 将 json 输出解码为模型

javascript - 如何在javascript中使用while循环打印数字

javascript - 流畅的动画

javascript - 我如何使用 jQuery 将一个按钮替换为另一个按钮

javascript - Ajax 调用 API 返回错误 HTTP/1.1 405 Method Not Allowed