我正在尝试使用Jquery解析来自远程URL的json数据。我的数据格式如下:
[
{
"UserId": "5",
"Name": "Syed",
"Lat": "23.193458922305805",
"Long": "77.43331186580654",
"EmailId": "syedrizwan@ats.in",
"LocationUpdatedAt": ""
},
{
"UserId": "98",
"Name": "Michael Catholic",
"Lat": "23.221318",
"Long": "77.42625",
"EmailId": "michaelcatholic@gmail.com",
"LocationUpdatedAt": ""
}
]
我已经检查了json-lint中的数据,它说这是正确的数据格式。当我尝试在HTML页面上运行它时,它会返回一个空白页面。我的HTML代码如下:
<html>
<head>
<title>Jquery Json</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$.getJSON('http://localhost/fbJson/json.php', function(results){
document.write(results.Name);
});
});
</script>
</head>
<body>
</body>
</html>
我正在尝试从json字符串
results
是一个项数组,因此您必须考虑您想要的项。
通常,你会以类似于的方式循环遍历数组
$.getJSON('http://localhost/fbJson/json.php', function(results){
for(var i = 0; i < results.length; i++) {
console.log(results[i].Name);
}
});
有一个对象数组,您可以使用索引直接访问它们
$.getJSON('http://localhost/fbJson/json.php', function(results){
document.write(results[0].Name);
});
如果您希望在数组上进行迭代,可以使用$.each
并将results
传递到中
$.each(results, function(key, val) {
document.write(val.Name);
});
您的json格式是正确的。使用此代码访问第一行数组中的名称:
document.write(results[0].Name);