2016-05-12 81 views
5

我一直在嘗試在過去的幾天使我的代碼工作,但我找不到問題。
我想與維基百科服務器進行通信並獲取他們的JSON API,以便我可以製作與searchInput的輸入值相對應的項目列表。
我一直在調查JSONP,最終發現我可以添加「& callback =?」我的API請求,它應該工作。 現在,儘管我已經添加了它,但溝通依然沒有發生。
我注意到,在處理「#searchInput」輸入後初始化代碼時,codepen.io上的控制檯返回「無標題」片刻。 也許問題出在我的for ... in循環中。 你知道我應該怎麼做嗎?
鏈接到我的代碼:http://codepen.io/nedsalk/pen/zqbqgW?editors=1010
(jQuery是在「設置」菜單中已經啓用)
如果你喜歡代碼的html的版本:使用JSONP訪問維基百科API

<!DOCTYPE HTML> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title> Object Oriented JavaScript </title> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"> </script> 
</head> 

<body> 
<h1> Wikipedia viewer </h1> 
<a href="http://en.wikipedia.org/wiki/Special:Randompage" target="_blank">Go random! </a> 
<form> 
<input type="text" name="searchInput" id="searchInput" placeholder="Search Wikipedia" 
onkeydown = "if (event.keyCode == 13) 
    document.getElementById('submit-button').click()"/> 
<input type="submit" id="submit-button"/> 
</form> 
<div id="list"></div> 
<script> 
$(document).ready(function() { 

    $("#submit-button").on("click",function(){ 
     var input=$("#searchInput").val(); 
     $.getJSON('https://en.wikipedia.org/w/api.php?action=query&generator=search&gsrsearch=' + encodeURIComponent(input) + '&prop=extracts&exlimit=10&exintro&exsentences=2&format=json&callback=?', 
      function(API){ 
       $("#list").empty(); 
       for (var id in API.query.pages) 
       {if(API.query.pages.hasOwnProperty(id){ 
        $("#list").html('<a target="_blank" href="http://en.wikipedia.org/?curid=' + id + '">' 
            +'<div id="searchList">' 
            + "<h2>" + id.title + "</h2>" 
            + "<br>" 
            + "<h3>" + id.extract + "</h3>" 
            + "</div></a><br>") 
       }} 

      }) 
     }) 
}) 
</script> 
</body> 
</html> 
+0

'&回調='的''這裏代表的是Ajax請求後,將接收到的數據的JavaScript函數的名稱,你」?需要創建該函數並用名稱替換'?'(請參閱jsonp https://en.wikipedia.org/wiki/JSONP –

+2

@VelimirTchatchevsky不,這將使用默認回調方法 –

回答

3

你在你的代碼的幾個問題:

  • 你應該勾到submit事件的形式,按鈕的不是click,並且使用event.preventDefault()停止提交。
  • 您可以遍歷返回對象的鍵並嘗試訪問這些字符串的屬性,而不是使用鍵訪問基礎屬性。
  • 您在每個循環中設置了html(),因此只有最後一個項目可見。您應該使用append()

試試這個:

$("form").on("submit", function(e) { 
    e.preventDefault(); 
    var input = $("#searchInput").val(); 
    $.getJSON('https://en.wikipedia.org/w/api.php?action=query&generator=search&gsrsearch=' + encodeURIComponent(input) + '&prop=extracts&exlimit=10&exintro&exsentences=2&format=json&callback=?', function(response) { 
     var pages = response.query.pages; 
     $("#list").empty(); 

     for (var id in pages) { 
      $("#list").append('<a target="_blank" href="http://en.wikipedia.org/?curid=' + id + '">' + 
       '<div id="searchList">' + 
       "<h2>" + pages[id].title + "</h2>" + 
       "<br>" + 
       "<h3>" + pages[id].extract + "</h3>" + 
       "</div></a><br>") 
     } 
    }); 
}); 

Working example

+0

非常感謝,工作!:D – nedsalk

+0

沒問題,很樂意幫忙 –