我想使用 star wars api 中的 JSON 数据进行实时搜索。 JSON 包含一些对象
,我想要获取的对象
是结果
,它是一个数组
,包含具有属性名称
、高度
、质量
等的对象
。
JSON 片段如下:
{
"count": 87,
"next": "http://swapi.co/api/people/?format=json&page=2",
"previous": null,
"results": [
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "http://swapi.co/api/planets/1/",
"films": [
"http://swapi.co/api/films/6/",
"http://swapi.co/api/films/3/",
"http://swapi.co/api/films/2/",
"http://swapi.co/api/films/1/",
"http://swapi.co/api/films/7/"
],
"species": [
"http://swapi.co/api/species/1/"
],
"vehicles": [
"http://swapi.co/api/vehicles/14/",
"http://swapi.co/api/vehicles/30/"
],
"starships": [
"http://swapi.co/api/starships/12/",
"http://swapi.co/api/starships/22/"
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "http://swapi.co/api/people/1/"
}
]
}
我尝试使用此代码,但控制台显示Uncaught TypeError: Cannot read property 'name' of undefined
(on line 7)
$('#search').keyup(function() {
var searchField = $('#search').val();
var myExp = new RegExp(searchField, "i");
$.getJSON('http://swapi.co/api/people/?format=json', function(data) {
var output = '<ul class="searchresults">';
$.each(data, function(key, val) {
if ((val.results.name.search(myExp) != -1) ||
(val.results.height.search(myExp) != -1)) {
output += '<li>';
output += '<h2>'+ val.name +'</h2>';
output += '<p>'+ val.height +'</p>';
output += '</li>';
}
});
output += '</ul>';
$('#update').html(output);
});
});
我知道我的循环有问题,我尝试寻找答案,但找不到正确的答案。你能帮我吗?
最佳答案
这是一个简单的错误,您应该迭代 data.results
$.getJSON('http://swapi.co/api/people/?format=json', function(data) {
$.each(data.results, function(key, val) {
console.log(val.name);
})
});
您的 JSON 包含:
- “计数”:87,
- “下一个”:“http://swapi.co/api/people/?format=json&page=2”,
- “上一个”:空,
- “结果”:您想要的数据
因此,您必须获得结果并对其进行迭代。
关于javascript - 如何使用 $.each JQuery 循环 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41672195/