Javascript Ajax在浏览器中读取和打印JSON-无法读取属性映射
我以前没有使用过jquery或ajax,所以我希望有人能对我遇到的问题有所了解 我已经完成了这里的教程Javascript Ajax在浏览器中读取和打印JSON-无法读取属性映射,javascript,jquery,ajax,Javascript,Jquery,Ajax,我以前没有使用过jquery或ajax,所以我希望有人能对我遇到的问题有所了解 我已经完成了这里的教程https://www.sitepoint.com/ajaxjquery-getjson-simple-example/使用我自己的json数据 我收到错误“UncaughtTypeError:无法读取未定义的属性“map” 我看不出我的代码与教程中的代码有什么不同(除了几个变量名),所以我不确定哪里出了问题。如有任何意见,将不胜感激 <!DOCTYPE html> <html
https://www.sitepoint.com/ajaxjquery-getjson-simple-example/
使用我自己的json数据
我收到错误“UncaughtTypeError:无法读取未定义的属性“map”
我看不出我的代码与教程中的代码有什么不同(除了几个变量名),所以我不确定哪里出了问题。如有任何意见,将不胜感激
<!DOCTYPE html>
<html>
<head>
<title>tutorial 01</title>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<button type="button" id="button">Load JSON</button>
<div id="show-data"></div>
<script>
$(document).ready(function () {
$('#button').click(function () {
var showData = $('#show-data');
$.getJSON('json.txt', function(data) {
console.log(data);
var items = data.items.map(function (item) {
return item.firstName + ' ' + item.lastName;
});
showData.empty();
if (items.length) {
var content = '<li>' + items.join('</li><li>') + '</li>';
var list = $('ul />').html(content);
showData.append(list);
}
});
showData.text('Loading the JSON file.');
});
});
</script>
</body>
您必须访问数据对象上的employees属性
var items = data.employees.map(function (item) {
return item.firstName + ' ' + item.lastName;
});
问题很可能是您使用了json文件。您应该发布json文件的副本,但是从代码中,您需要json中的一个名为“items”的对象。
data。items
应该是data。employees
,否?完美。这是正确的。我只是不熟悉如何访问json数据。我感谢你的帮助!只要时间允许,我会尽快接受答复。
var items = data.employees.map(function (item) {
return item.firstName + ' ' + item.lastName;
});