我是维基百科api调用,页面在jquery ajax调用后自动重新加载。页面内容显示然后重新加载

时间:2016-05-12 13:31:29

标签: javascript jquery json ajax

我是jquery通过点击维基百科上搜索文章的按钮进行api调用.ajax工作正常,内容也会显示然后重新加载。显示内容消失。

<h1>Wikipedia Viewer</h1>
<form class="form-inline">
  <div class="container">
    <div class="row">
      <div class="col-sm-6 col-sm-offset-4 col-lg-7 col-lg-offset-4">
        <div class="form-group">
          <label class="sr-only" for="search">search</label>
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-primary"><i class="fa fa-search"></i></button></form>
</div>
</div>
</div>
<a href="https://en.wikipedia.org/wiki/Special:Random">Surprise me!</a>
$(document).ready(function() { 
  $("button").click(function() { 
    var article = $("input").val();  //extract value from input box
    $.ajax({                               //wikipedia api call
      url: "https://en.wikipedia.org/w/api.php?  action=query&list=search&srsearch=" + article + "&format=json", 
      dataType: "jsonp",
      success: function(data) {                  
        for (var i = 0; i < data.query.search.length; i++) {  //looping through json 
          var title = data.query.search[i].title;             //adding data on page
          var snippet = data.query.search[i].snippet;
          $("button").append("<p>" + title + "</p>");
          $("p").append("<p>" + snippet + "</p>");
        }
      },
      error: function() {
        $("h1").html("oops");
      }
    });
  });
});
    here is my codepen link
[1]: https://codepen.io/shubhamshukla1994/pen/YqgLXW

1 个答案:

答案 0 :(得分:1)

只需更改类型=&#34的按钮元素;提交&#34;输入=&#34;按钮&#34;。更新了https://codepen.io/anon/pen/Yqgoyg

<h1>Wikipedia Viewer</h1>
<form class="form-inline">
  <div class="container">
    <div class="row">
      <div class="col-sm-6 col-sm-offset-4 col-lg-7 col-lg-offset-4">
        <div class="form-group">
          <label class="sr-only" for="search">search</label>
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="button" class="btn btn-primary"><i class="fa fa-search"></i></button></form>
</div>
</div>
</div>
<a href="https://en.wikipedia.org/wiki/Special:Random">Surprise me!</a>