在 jQuery 代码中,您应该有 employees 属性。
data.employees[0].firstName
所以应该是这样的。
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$.getJSON("names.json", function(data) {
console.log(data);
$('body').append(data.employees[0].firstName);
});
</script>
</body>
</html>
当然,非 jQuery 版本也需要该属性,但您需要先解析 JSON 响应。
还请记住,document.write 正在破坏您的整个页面。
如果您仍然遇到问题,请尝试完整的 $.ajax 请求,而不是 $.getJSON 包装器。
$.ajax({
url: "names.json",
dataType: "json",
success: function(data) {
console.log(data);
$('body').append(data.employees[0].firstName);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('ERROR', textStatus, errorThrown);
}
});
http://api.jquery.com/jquery.ajax/