无法读取未定义的属性“搜索”(维基百科API)

时间:2016-01-10 17:19:12

标签: javascript json api wikipedia

我正在搞乱维基百科API,但我一直收到错误;

“无法读取未定义的属性'搜索'

有人可以解释我做错了什么吗?当用户使用搜索栏尝试查找内容时,我会使用.map来浏览数据并将数据结果粘贴到我的resultDiv中。

这是我的代码; &安培;一个强制性的codepen。 http://codepen.io/pixeluh/pen/wMdpbM?editors=101

$(document).ready(function() {

  var searchBar = $("#search");
  var resultDiv = $(".results");
  var goButton = $("#go");

  $.ajax({
    url: "http://en.wikipedia.org/w/api.php?",
    data: {
      action: 'query',
      list: 'search',
      srsearch: searchBar.val(),
      format: 'json'
    }, //end of data
    dataType: 'jsonp',
    success: function(data){
        var datatp = '';
        data.query.search.map(function(f) {
            datatp += f.title;
            datatp += f.snippet;
          }) //end of map
        resultDiv.html(datatp);
      } //end of success
  }); //end of ajax

}); //end of body func
<html>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<container id="page">
  
  <div id="flex-container">
  <div class="search-bar">
    <form class="searchbar">
      <input type="search" name="wikisearch" placeholder="Search wiki..." id="search">
      <input type="submit" id="go" value="Go"/>
      
      <input type="button" id="random" value="Random" onclick="window.location ='http://en.wikipedia.org/wiki/Special:Random';"/>
      
    </form>
   
  </div>
  </div>
  
  <div class="results">
    <!-- search results go here-->
  </div>
  
</container>
</html>

感谢您的任何帮助或指导,谢谢。

1 个答案:

答案 0 :(得分:0)

您已准备好调用ajax但它应该像这样提交:

$(document).ready(function() {

  var searchBar = $("#search");
  var resultDiv = $(".results");
  var goButton = $("#go");
  $('form').submit(function() {
    $.ajax({
      url: "https://en.wikipedia.org/w/api.php?",
      data: {
        action: 'query',
        list: 'search',
        srsearch: searchBar.val(),
        format: 'json'
      }, //end of data
      dataType: 'jsonp',
      success: function(data){
          var datatp = '';
          data.query.search.map(function(f) {
              datatp += f.title;
              datatp += f.snippet;
            }) //end of map
          resultDiv.html(datatp);
        } //end of success
    }); //end of ajax
    return false;
  });
}); //end of body func

<强> JSFIDDLE