我在 test.php
上有一个像这样的数组。
Array(
[0] => Array
(
[id] => 1
[name] => nikhil
[password] => 81dc9bdb52d04dc20036dbd8313ed055
)
[1] => Array
(
[id] => 2
[name] => akhil
[password] => 81dc9bdb52d04dc20036dbd8313ed055
)
)
我将其转换为 JSON 并回显它
$jsonformat = json_encode($array);
echo $jsonformat;
然后我在 test.php
上得到一个像这样的 JSON 字符串
[{
"id": 1,
"name": "nikhil",
"password": "81dc9bdb52d04dc20036dbd8313ed055"
},{
"id": 2,
"name": "akhil",
"password": "81dc9bdb52d04dc20036dbd8313ed055"
}]
现在如何使用 AJAX 调用以 JSON 形式访问此字符串。我只想访问此 JSON 对象第一行的名称。我试过这个:
$.ajax({
type: 'post',
url: '/test.php',
datatype: 'JSON',
success: function(result) {
alert(result[0].name);
}
});
但这不起作用。有什么建议吗?
最佳答案
Javascript 区分大小写。您将数据类型设置为 json
,以便 jQuery 知道期望返回什么并自动解析它。
但是,数据类型的正确键是 dataType
而不是 datatype
。
所以你需要:
$.ajax({
type: 'post',
url: '/test.php',
dataType: 'JSON',
success: function(result) {
alert(result[0].name);
}
});
关于php - 为什么我无法以 json 形式访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39973289/