我有一个 PHP 文件,它为我的 MySQL 数据创建一个 JSON 文本。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>Sample Page</title>
<script>
var settings = {
"async": true,
"crossDomain": true,
"url": "http://www.hotel1.com/Experiment/Api/Json1.php?ID=1",
"method": "GET"
}
$.ajax(settings).done(function (response) {
console.log(response);
console.log(response.something.something)
});
</script>
上面你可以看到我的代码
[
{
"Worker1": {
"ID :": "1",
"Username": "Tony"
}
}
]
在上面你可以看到我正在打印的 JSON 文本。我的问题是我想知道如何从 JavaScript 中的 JSON 文本中选择 ID。如上所示。当我尝试说 response.Worker1.ID 时,它给我一个错误,指出 ID 未定义。
谁能帮我改正我的错误?
最佳答案
您需要将 JSON 解析为 javascript 对象。使用JSON.parse()
,如下:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>Sample Page</title>
<script>
var settings = {
"async": true,
"crossDomain": true,
"url": "http://www.hotel1.com/Experiment/Api/Json1.php?ID=1",
"method": "GET"
}
$.ajax(settings).done(function (response) {
response = JSON.parse(response); // the change is here
console.log(response);
console.log(response.something.something)
});
</script>
另请记住,您的“示例 json”返回一个数组,因此方括号 []
。因此,要访问,您需要执行 response[0].something
。
关于javascript - 如何获取JSON文本的特定部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65261933/