我想使用來自star wars api的JSON數據進行實時搜索。 JSON包含一些objects
,我想獲取的objects
是results
,這是一個array
,其中包含objects
,它們具有屬性name
,height
,mass
等。
的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
(第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);
});
});
我知道有什麼毛病我的循環,我試圖尋找答案,但我無法得到正確的答案。你能幫我麼?
'Val'在'undefined'中,因此'val.name'不是RK。你有沒有證實終端給你格式化的json? – Automatico
結果是數組,而不是對象的屬性,你必須迭代結果到訪問名稱 –
@Akshaypadwal是的,我說'結果'是包含對象的數組 – bnrfly