javascript - 如何获取 JSON 文本的特定部分
问题描述
我有一个 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
.