需要帮助理解 .getJSON() 行为

Need help understanding .getJSON() behavior

本文关键字:行为 getJSON 帮助 助理      更新时间:2023-09-26

我试图理解为什么 .getJSON() 调用会在表单提交未被抑制时引发错误。最初我认为表单提交可能意味着函数wikiCall()没有被启动。但是,当表单在输入时提交时,正确的"wikiLink"[wikiCall()的参数]会打印在控制台中,但这会导致.getJSON()失败。

该目录

<div class="text-center searchBar">
  <form action="">
    <input type="text" id="searchText" />
  </form>
</div>
<div class="container displayResults"> </div>

Javascript:

$(document).ready(function() {
   $('#searchText').keypress(function(e) {
     var searchItem = $('#searchText').val();
     var link = 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&exlimit=max&inprop=url&generator=search&gsroffset=&format=json&formatversion=2&callback=?&gsrsearch=' + searchItem;
     if(e.which == 13) { //if user returns enter key
      wikiCall(link);
      //e.preventDefault(); //.getJSON throws error if form submission is not suppressed
     }    
   });
});
function wikiCall(wikiLink) { 
  console.log(wikiLink); //prints the correct link even on form submit
  $.getJSON(wikiLink, function(searchResults) {      
    for (var i = 0; i < searchResults.query.pages.length; i++) {
      $(".displayResults").append("<div class='searchResultsContainer'><span style='font-weight:bold; font-size:150%; margin-bottom:100px;'>" + searchResults.query.pages[i].title + "</span><br></br>" + searchResults.query.pages[i].extract + "</div>");
      $(".displayResults").append("<br>");
    }
  }).fail(function(jqxhr,textStatus,error){
    alert(textStatus+": "+error); //shows error:error if form is submitted on enter
  });
}

因为 form 元素上的 action 属性是一个空字符串,所以通过提交表单,您可以有效地刷新页面,这会导致浏览器中止所有打开的 Ajax 请求,从而在离开页面之前触发错误处理程序。除非您的主机在页面之间保留日志,否则错误消息应仅在加载下一页之前显示一小段时间。

您的代码目前没有多大意义,如果您不希望启动浏览器的导航,则应始终阻止提交表单的默认行为。

你为什么不从提交发送请求。

$(document).ready(function() {
   $('form').on('submit', function(e) {
     e.preventDefault();
     var searchItem = $('#searchText').val();
     var link = 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&exlimit=max&inprop=url&generator=search&gsroffset=&format=json&formatversion=2&callback=?&gsrsearch=' + searchItem;
      wikiCall(link);
   });
});
function wikiCall(wikiLink) { 
  console.log(wikiLink); //prints the correct link even on form submit
  //clean the div before append the new result;
  $(".displayResults").html('');
  $.getJSON(wikiLink, function(searchResults) {      
    for (var i = 0; i < searchResults.query.pages.length; i++) {
      $(".displayResults").append("<div class='searchResultsContainer'><span style='font-weight:bold; font-size:150%; margin-bottom:100px;'>" + searchResults.query.pages[i].title + "</span><br></br>" + searchResults.query.pages[i].extract + "</div>");
      $(".displayResults").append("<br>");
    }
  }).fail(function(jqxhr,textStatus,error){
    alert(textStatus+": "+error); //shows error:error if form is submitted on enter
  });
}

这是一个提交代码和表单的工作示例,只需键入并按回车键即可。 http://jsbin.com/hexoyocusa/edit?html,js,output