使用用户输入动态提交api请求

时间:2016-09-28 18:34:10

标签: javascript wikipedia-api

我正在尝试使用用户填写的表单向Wikipedia API提交搜索请求。但是,在提交表单时,页面将刷新并且不执行任何操作。我试图" preventDefault",但没有完成任务。我将在下面发布我的html和javascript代码(如果我的css在某种程度上有帮助,我当然可以提供它。)

HTML:

<body>

  <div class="random text-center">
    <a target="_blank" href ="http://en.wikipedia.org/wiki/Special:Random">Get a Random Entry</a>
  </div>
  <br/>
  <div class="text-center">
    <form>
  <input type="text" placeholder="search" id="search">
      <input type="submit">
    </form>
  </div>

  <div class="results">
  </div>

</body>

Javascript:

$(document).ready(function(){


  $('#search').submit(search());


function search(){

  var value = ("#search").val();
  //var value = "eggs";
  $.getJSON("https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + value + "&utf8=&format=json&callback=?", function(json) {
  json.query.search.forEach( function(val) {
    var title = val.title;
    var snippet = val.snippet;
    titleURL = title.replace(/ /g, "_");


    $(".results").append("<a target='_blank' href='https://en.wikipedia.org/wiki/" + titleURL +"'><div class='result'><div class='title'>" + title + "</div><br/><div class='snippet'>" + snippet + "</div></div></a><br/>")

  });

  var title = json.query.search[0].title;
  var snippet = json.query.search[0].snippet;
});

};
});

codepen:

http://codepen.io/blarmon/pen/rrZzyB

0 个答案:

没有答案