从两个AJAX请求构造JavaScript对象

时间:2014-05-31 10:03:46

标签: javascript jquery ajax json object

我有一个API,用于获取代表Boats的对象数组,它返回一个" id"," name"," length"和" harbour_id"对于每艘船。

我还有另一个API来获取" harbour_name"来自" harbour_id"。虽然为两者编写AJAX请求不是问题,但令我困惑的是:我必须构建一个对象数组,其中每条船都包含itsef的所有数据," harbour_name"包括在内。

我该怎么做?

让我们写一些代码:

var boats;
function getBoats() {
    $.ajax({
    url:'/',
    type:'GET',
    success: gotBoats,
    error: didntGetBoats,
    });
}

function gotBoats(data, textStatus, jqXHR) {
    boats = $.parseJSON(data);
        // I presume I need to make another request somewhere around here
        // but I'm not sure how to do it to bind the response data to
        // the correct boat
}

function didntGetBoats(jqXHR, textStatus, errorThrown) {
    alert(errorThrown);
}

在这个问题解决之后,我还需要能够向后做 - 输入一条新船并将它的位置发布到适当的位置,其余数据到达它的适当位置

提前感谢您提示:)

1 个答案:

答案 0 :(得分:2)

您无需一个更多请求,您将不得不请求每条船,这将是非常低效的。如果有任何方法可以在第一个回复中包含港口名称,那就是您想要做的事情。

但是,如果你不能,你可以发起一系列船只请求:

function gotBoats(data, textStatus, jqXHR) {
    // Somethign to keep track of how many harbour name responses we've seen
    var harbourNameCount = 0;

    // Get the boats. (Do you need that parseJSON call? jQuery will
    // do it automatically if the Content-Type of the response is correct;
    // or you can add `dataType: 'json'` to the `ajax` call.)
    boats = $.parseJSON(data);

    // Loop through requesting harbour names
    $.each(boats, function(i, boat) {
        // Ask for this harbour name, using ES5's Function#bind to
        // pass the relevant boat into the callbacks. You'll need
        // a shim for Function#bind on IE8 and earlier.
        $.ajax({
            url:      "/path/to/harbour/name/query",
            data:     {harbour_id: boat.harbour_id},
            success:  gotHarbour.bind(null, boat),
            error:    didntGetHarbour.bind(null, boat),
            complete: finishHarbour
        });
    });

    // Callback for when we get the name; note that since we use this
    // with bind, the boat is our first argument.
    function gotHarbour(boat, data) {
        boat.harbour_name = data.harbour_name;
    }

    // Callback for when we don't get the name for some reason
    function didntGetHarbour(boat) {
        boat.harbour_name = "(Unknown: " + boat.harbour_id + ")";
    }

    // Called after the two callbacks above
    function finishHarbour() {
        // Count this response
        ++harbourNameCount;

        // If we have seen all the responses, we're done!
        if (harbourNameCount === boats.length) {
            allFinishedLoading();
        }
    }
}