简体   繁体   English

jQuery-如何从内部Ajax调用接收结果?

[英]jQuery - how to receive result from an inner ajax call?

I am developing an web app in which the user will be able to identify the location from map by clicking on the map (I use jquery 3.1 ). 我正在开发一个Web应用程序,用户可以在其中通过单击地图来识别地图上的位置(我使用jquery 3.1 )。 The problem is that I have to make some ajax calls, one depend on other, and on the last call the result it's not returned as a whole (full array) and I received only a part of array. 问题是我必须进行一些ajax调用,一个依赖于另一个调用,并且在最后一次调用时,结果没有作为一个整体(完整数组)返回,而我仅收到一部分数组。

The problem survives from var a4 . 该问题在var a4中仍然存在。

How I can make that a4 result to be send as a full array because I tried with deferred but with no expecting result? 我如何使a4结果作为完整数组发送,因为我尝试了延迟但没有预期的结果?

var getLocDetails = function () {
    // Parse a web api based on user lat & lon
    var a1 = $.ajax({
        method: 'GET',
        url: 'http://nominatim.openstreetmap.org/reverse?lat=44.43588&lon=26.04745&accept-language=ro&format=json'
    });

    // Get osm_type & osm_id and parse another web service to get a XML document (Ex.: https://www.openstreetmap.org/api/0.6/way/28240583)
    var a2 = a1.then(function (data) {
        return $.ajax({
            method: 'GET',
            url: 'https://www.openstreetmap.org/api/0.6/' + data.osm_type + '/' + data.osm_id
        })
    });

    // Get all 'ref' attribute from every 'nd' node from XML and make an array with this values
    var a3 = a2.then(function (data) {
        var osmChildren = data.documentElement.childNodes;
        var out = [];

        for (var i = 0; i < osmChildren.length; i++) {
            if (osmChildren[i].nodeName == 'way') {
                var wayChildren = osmChildren[i].childNodes;
                for (var j = 0; j < wayChildren.length; j++) {
                    if (wayChildren[j].nodeName == 'nd') {
                        var ndRef = Number.parseInt(wayChildren[j].getAttribute('ref'));
                        out.push(ndRef);
                    }
                }
            }
        }
        return out;
    });

    // HERE IS THE PROBLEM
    // Based on array returned from a3, I am parsing every link like 'https://www.openstreetmap.org/api/0.6/node/ + nodeRef' to extract every lat and lon values for extreme points
    var a4 = a3.then(function (data) {
        var defer = $.Deferred();
        var out = [];

        for (var i = 0; i < data.length; i++) {
            var nodeRef = data[i];
            var nodeUrl = 'https://www.openstreetmap.org/api/0.6/node/' + nodeRef;

            $.ajax({
                method: 'GET',
                url: nodeUrl
            }).done(function (response) {
                var node = response.documentElement.firstElementChild;
                var lat = Number.parseFloat(node.getAttribute('lat'));
                var lng = Number.parseFloat(node.getAttribute('lon'));

                out.push([lat, lng]);
                defer.resolve(out);
            });
        }
        return defer.promise();
    });

    // When a4 is done, based his result, I have to have an array of lat & lon coordonates, but I recived only 1-2 coordonates even I have 10.
    a4.done(function (data) {
        console.log(data);
        // Here I have to draw a polygon
    });
}

you need to handle the requests in an array, as what you are doing tends to resolve the callback for a4 before all are complete. 您需要处理数组中的请求,因为您执行的操作往往会在完成所有操作之前解决a4的回调。

To do this we can use $.when function 为此,我们可以使用$.when函数

var req = [];
// Based on array returned from a3, I am parsing every link like 'https://www.openstreetmap.org/api/0.6/node/ + nodeRef' to extract every lat and lon values for extreme points
var a4 = a3.then(function (data) {
    var defer = $.Deferred();
    var out = [];

    for (var i = 0; i < data.length; i++) {
        var nodeRef = data[i];
        var nodeUrl = 'https://www.openstreetmap.org/api/0.6/node/' + nodeRef;

        req.push(
            $.ajax({
                method: 'GET',
                url: nodeUrl
            }).done(function (response) {
                var node = response.documentElement.firstElementChild;
                var lat = Number.parseFloat(node.getAttribute('lat'));
                var lng = Number.parseFloat(node.getAttribute('lon'));
                out.push([lat, lng]);
            })
       );
    }
    $.when.apply($, req).done(function(){
        return defer.resolve(out);
    });
    return defer.promise();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM