gpt4 book ai didi

javascript - 从两个 AJAX 请求构造一个 JavaScript 对象

转载 作者:行者123 更新时间:2023-11-29 14:52:12 25 4
gpt4 key购买 nike

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

我还有另一个 API,用于从“harbour_id”获取“harbour_name”。虽然为两者编写 AJAX 请求不是问题,但令我困惑的是:我必须构建一个对象数组,其中每艘船都包含其自身的所有数据,包括“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);
}

解决这个问题后,我还需要能够反向执行 - 输入一艘新船并将其位置发布到适当的位置,并将其余数据发布到适当的位置。

提前感谢您的提示:)

最佳答案

您不必再一个请求,您必须为每艘船请求,这将是非常低效的。如果有任何方法可以让港口名称包含在第一个响应中,那就是您想要做的。

但如果你做不到,你可以触发对船只的一系列请求:

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

关于javascript - 从两个 AJAX 请求构造一个 JavaScript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23968694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com