【问题标题】:Jquery AjaxStop not firing while AjaxStart doesAjaxStart 执行时 Jquery AjaxStop 未触发
【发布时间】:2018-02-12 02:50:31
【问题描述】:

我在体验 API 时发现自己遇到了一些问题。

我有从 api 获取数据的 Jquery 函数,为了不产生“重新定位”效果,我需要该函数等待所有调用完成,然后再触发另一个放置所有 api 的函数日期到位。

我尝试使用 AjaxStart 和 AjaxStop,但是虽然第一个可以完美运行,但第二个不能,我不知道为什么...

我正在构建的应用程序很大,所以我制作了一个 codePen 来简化我的问题:

HTML:

<div id="button"></div>
<div id='locationbox'>
  <span id='city'>Get the country</span>
  <img id = "countryimg" src="">
  <div id='searching'> searching...</div>
</div>

CSS

#button{
  height : 150px;
  width : 150px;
  border : 5px solid black;
  border-radius : 50%;  
  position : absolute;
  top : 45%;
  left : 45%;
}
#locationbox{
  text-align : center;
  width : 300px;
  position : absolute;
  top : 25%;
  left : 38.5%;

}

JavaScript:

$("#button").on('click',function(){
  getCity();

});

$(document).ajaxStart(function() {
  $("#city").html("fetching data");

});
$(document).ajaxStop(function() {
  $("#searching").html("Success")    
});

function getCity(){
$.ajax({
  datatype : "json",
  contentType : "application/json",
  type : "GET",
  url : "https://nominatim.openstreetmap.org/reverse?",
  data : {
    format:"json",
    lat :"50.8503",
    lon : "4.3517",
    zoom:"18",
    adressdetails:"1"
  },
  success : function(quote){
    var city = quote.address.city;
    var country = quote.address.country
    var countryCode = quote.address.country_code.toUpperCase()
    document.getElementById("city").innerHTML = city + " , " + country;
    document.getElementById("countryimg").src = "http://www.geognos.com/api/en/countries/flag/" + countryCode + ".png";
    document.getElementById("country").innerHTML = country;
  },
  error : document.getElementById("city").innerHTML = "error!"
});
};

正如您在this code pen 中看到的,当 AjaxStart 触发时,AjaxStop 不会。感谢阅读,感谢大家对我的帮助。

【问题讨论】:

    标签: javascript jquery ajax api triggers


    【解决方案1】:

    发生这种情况是因为您的成功代码块中存在错误。由于这个错误,您的 ajaxStop 不会执行。

    删除 document.getElementById("country").innerHTML = country; 行,因为文档中没有具有该 ID 的元素。否则,添加一个id为country的元素

    检查工作代码笔https://codepen.io/anon/pen/NyjMOQ

    【讨论】:

    • 哦,这很简单 :D 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多