【问题标题】:How to use form data in codepen如何在codepen中使用表单数据
【发布时间】:2017-02-06 08:31:35
【问题描述】:

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

理想情况下,我只想让用户输入一些文本,然后在用户点击提交时将其变为我的代码中的字符串。这是目前搜索栏的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);

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

【问题讨论】:

    标签: javascript html forms wikipedia-api codepen


    【解决方案1】:

    可以使用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-07-02
    • 2022-11-28
    • 2018-12-16
    • 2020-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-20
    相关资源
    最近更新 更多