检测何时完成ajax [英] detect when ajax is done

查看:61
本文介绍了检测何时完成ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我要从json文件中获取一些邮政编码.完成加载后,我遍历邮政编码并连接到

First, I'm grabbing some zip codes from a json file. After that is done loading, I loop through the zip codes and connect to

http://api.geonames.org/postalCodeSearchJSON?postalcode="+zip+"&maxRows=1&username=demo

,并用每个邮政编码的邮政编码替换"zip".因此,如果我有30个邮政编码,它将调用此URL 30次,并获取每个邮政编码的纬度和经度,并将它们放置在数组中.

and replace "zip" with the zip code foreach zip code. So if I have 30 zip codes, it calls this URL 30 times and grabs the Latitude and Longitude for each zip code and places them in an array.

问题是,在ajax调用完全构建数组之前,我正在尝试使用它.我正在做的一项工作是执行setTimeout()3秒钟,以便浏览器有时间完全构建数组,然后可以使用它.

The problem is, I'm trying to use my array before it's being fully built by the ajax call. A work around I'm doing is doing a setTimeout() for 3 seconds so the browser has time to fully build the array and then I can use it.

我当前正在使用

$.getJSON( "zip-codes.json", function(){}).done(function(locations){
    // this .done() isnt actually working
});

下面是我的所有代码:

var marker_object = new Array;
// get location zip codes
$.getJSON( "zip-codes.json", function(){}).done(function(locations){

    // for each zip code
    $(locations.nodes).each(function(i, location_value){
        var name = location_value.node.city+', '+location_value.node.state+'\n'+location_value.node.phone;
        var zip = location_value.node.zip;
        // if zip is not empty
        if(zip != ''){

            // get lat, long for each zip
            $.getJSON( "http://api.geonames.org/postalCodeSearchJSON?postalcode="+zip+"&maxRows=1&username=midnetmedia", function(){}).done(function(long_lat){
                // loop thru each zip code, even tho we only return 1 value at a time
                $(long_lat.postalCodes).each(function(k,long_lat_value){
                    marker_object.push({latLng: [long_lat_value.lat, long_lat_value.lng], name: name});
                });
            }); // get lat, long for each zip

        } // if not empty
    }) // foreach location

}); // get zip codes

setTimeout(function(){
    console.log( marker_object );
}, 3000);

"marker_object"的最终结果在最终构建时看起来像这样

The end result for the "marker_object" looks something like this when it's finally built

marker_object = [
    {latLng: [34.079351, -117.455114], name: 'City 1'},
    {latLng: [24.079351, -67.455114], name: 'City 2'},
    {latLng: [14.079351, -36.455114], name: 'City 3'},
    ...
]

我怎么知道我的$ .getJSON何时完成?因为.done()对我不起作用.我应该改用$ .AJAX()吗?

How can I tell when my $.getJSON is actually done? because .done() isnt working for me. Should I be using $.AJAX() instead?

推荐答案

使用 .ajaxComplete()事件.

$(document).ajaxComplete(function(event, xhr, settings) {
  alert("Ajax Complete")
});

根据其文档,

每当Ajax请求完成时,jQuery都会触发ajaxComplete事件.

这篇关于检测何时完成ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆