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

Need help understanding .getJSON() behavior

我想了解为什么在未禁止提交表单时 .getJSON() 调用会引发错误。最初我认为也许表单提交意味着函数 wikiCall() 没有被启动。但是,当输入时提交表单时,控制台会打印正确的“wikiLink”[wikiCall() 的参数],但这会导致 .getJSON() 失败。

HTML

<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
  });
}

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

$(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

因为 form 元素上的 action 属性是一个空字符串,提交表单实际上是在刷新页面,这会导致浏览器中止所有打开 Ajax请求,从而在离开页面之前触发错误处理程序。除非您的控制台在页面之间保留日志,否则错误消息应该只会在加载下一页之前出现很短的时间。

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