[英]$.getJSON returns undefined then returns requested data
我陷入困境。 我當時正在為個人練習項目編寫Wikipedia搜索工具,但遇到一個小錯誤。 當用戶在搜索欄中輸入單詞時,輸入內容將存儲到$.getJSON
的數據參數中,然后響應將根據在搜索欄中輸入的單詞返回標題和描述對象的數組。 $.getJSON
函數將以指定HTML的列表格式顯示5組標題及其描述。 很簡單,但是問題在於$.getJSON
函數將顯示$.getJSON
"undefined"
,然后繼續顯示所需的標題和描述集。 下面我列出了我的JS編碼供您查看。 另外,完整的代碼也可以在我的codepen上查看。
誰能給我一個可能是問題的提示。 由於$.getJSON
是異步的,這可能是個問題,但是我不能完全依靠它。 提前致謝!
$("#search-word").on("keydown", function(event) {
if(event.keyCode == 13) {
event.preventDefault();
var input = {search: $(this).val()};
getWikiInfo(input);
}
});//search end
function getWikiInfo(input) {
var wikipApi = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&callback=?";
var getWikipHtml = function(response) {
console.log(response);
var wikipHtml;
for(var i = 1; i < 6; i++) {
wikipHtml += '<div class="list"><h3>' + response[1][i] + '</h3><p>' + response[2][i] + '</p></div>';
}
$("#list-container").html(wikipHtml);
}
$.getJSON(wikipApi, input, getWikipHtml);
}//getWikiInfo end
您需要進行一些小的更改。 將wikipHtml
初始化為空字符串,然后檢查response[1][i]
是否undefined
。 下面是更新的代碼:
var wikipHtml = '';
for (var i = 1; i < 6; i++) {
if (response[1][i] !== undefined)
wikipHtml += '<div class="list"><h3>' + response[1][i] + '</h3><p>' + response[2][i] + '</p></div>';
}
發生這種情況是因為您沒有在添加wikipHtml
之前wikipHtml
進行初始化,但是我強烈建議您使用適當的DOM操作,而不是使用字符串連接來構建HTML:
$("#search-word").on("keydown", function(event) { if (event.keyCode == 13) { event.preventDefault(); var input = { search: $(this).val() }; getWikiInfo(input); } }); //search end function getWikiInfo(input) { var wikipApi = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&callback=?"; var getWikipHtml = function(response) { var content = [0, 1, 2, 3, 4, 5].map(function(i) { return $('<div class="list">') .append($('<h3>').text(response[1][i])) .append($('<p>').text(response[2][i])); }); $("#list-container").html(content); } $.getJSON(wikipApi, input, getWikipHtml); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id='search-word' type='text' /> <div id='list-container'></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.