0

我正在开发免费代码营的维基百科查看器,并且正在尝试使搜索栏正常工作。

理想情况下,我只想让用户输入一些文本,然后在用户点击提交时将其变为我的代码中的字符串。这是到目前为止搜索栏的 html

<form method="get">
      <input type="text" placeholder="Search articles" class="srchbox" name="Search" id="searchbar">
      <button type="submit" class="btn">Search</button>
</form> 

以及我必须进行搜索的 api 设置

var apiURL = "https://en.wikipedia.org/w/api.php?format=json&action=opensearch&generator=search&search=" + textInput;

$(document).ready(function() {  
  $.ajax({
    url: apiURL,
    dataType: "jsonp",
    success: function(data) {
      var wikiAPI = JSON.stringify(data, null, 3);
      console.log(wikiAPI);  

      var wikiHTML = "";

        for (i=0; i < data[1].length; i++)
        {
          wikiHTML += ("<a href =\"" + data[3][i] + "\" target=\"_blank\">")
          wikiHTML += "<div class = \"wikicontent container-fluid\" style = \"color:black;\">";
          wikiHTML += ("<h2>" + data[1][i] + "</h2>");
          wikiHTML += ("<h3>" + data[2][i] + "</h3>");
          wikiHTML += "</div></a>"
        }
      $("#articles").html(wikiHTML);

我对如何解决这个问题有点迷茫,所以任何帮助都会很棒。谢谢!

4

1 回答 1

0

您可以使用submit事件,将查询设置为#searchbar .value

$("form").on("submit", function(e) {
  e.preventDefault();
  if (this.searchbar.value.length) {
    var url = "https://en.wikipedia.org/w/api.php?format=json"
              + "&action=opensearch&generator=search&search=" 
              + this.searchbar.value;
    $.ajax({url:url, /* settings */});
  }
});
于 2017-02-06T08:39:24.093 回答