2010-09-15 125 views
2

我有此JSON爲什麼仍然是空的數據

{"suggestions":["M.I.A.","M.","Mindless Self Indulgence","The Cure","Telefon Tel Aviv","M","J. Ralph","Jason Mraz","Carbon Based Lifeforms","Cycle of Pain","Chantal Kreviazuk","-M-","ayumi hamasaki","R.E.M.","Donny McCaslin","Penfold","HEALTH","R. Kelly","DJ Khaled","Eminem","Spose","T.I.","The Lonely Island","H.I.M. (His Infernal Majesty)","Dropkick Murphys","Taylor Swift"],"query":"m"} 

對此我從這個Ajax調用

$.getJSON('<%= ajax_path("artistName") %>', req, function(data) { 
    //create array for response objects 
    var suggestions = []; 
    console.log(data); 
    //process response 
    $.each(data, function(i, val){         
     suggestions.push(val.name); 
    }); 
    console.log(suggestions); 
    //pass array to callback 
    add(suggestions); 
}); 
}, 

越來越爲什麼我的建議還是空

回答

2

你不必爲了循環,suggestions已經是可供使用的陣列,所以替換爲:

var suggestions = []; 
console.log(data); 
//process response 
$.each(data, function(i, val){         
    suggestions.push(val.name); 
}); 
console.log(suggestions); 

有了這個:

var suggestions = data.suggestions; 
console.log(suggestions); 

那麼你的數組傳遞給add()會從你的JSON響應的結果。

相關問題