gpt4 book ai didi

javascript - 我怎样才能对 jQuery AJAX 查询进行分组?

转载 作者:行者123 更新时间:2023-11-30 13:25:31 25 4
gpt4 key购买 nike

我有一些代码看起来像这样(我省略了对问题不重要的部分):

$.ajax({  
type: "POST",
url: "prepXML.php",
data: "method=getartists&user=" + userName + "&amount=" + amount,
dataType: "xml",
success: function(xml) {
$("artist", xml).each(function(){
// calculate and output some stuff and then call getTracks()
getTracks(artistName, artistNamePOST, artistPlaycount, divId, artistId);
});
}
});

function getTracks(artistName, artistNamePost, artistPlaycount, divId, artistId){
$.ajax({
type: "POST",
url: "prepXML.php",
data: "method=gettracks&user=" + userName + "&artist=" + artistNamePOST + "&playcount=" + artistPlaycount,
dataType: "xml",
success: function(xml){
// calculate and output some stuff
});
}
});

当它运行时,它会调用 getTracks() 五十次并在很短的时间内产生相当多的(服务器)CPU 负载,直到全部完成。我想做的是一次将 AJAX getTrack() 查询分组,例如 5,等到这五个完成,然后调用下五个,等到下五个完成,调用下五个等。这样做的目的是基本上在同一时间进行更少的查询(更少和更均匀地分布 CPU 负载)。

我不确定如何或什至可以做到这一点,因为它在某种程度上超过了 AJAX 的要点,但如果可能的话,我仍然希望完成这项工作。有人可以指出我正确的方向吗?谢谢。

为了更好地了解我需要它做什么以及应用程序的作用,这里有一个指向 app 的链接.它可以用任何 lastfm 昵称来试用(如果你没有,你可以使用我的 - “pootzko”)。我希望允许我将链接放在帖子中(?),如果没有,请随时将其删除..

最佳答案

我会考虑只检索用户点击过的艺术家的轨道信息。或者可能通过单个请求检索所有数据(可能在检索到数据后通过setTimeout() 分批处理)。

但是,如果一次只执行五个请求,则以下内容可能会奏效:

$.ajax({  
type: "POST",
url: "prepXML.php",
data: "method=getartists&user=" + userName + "&amount=" + amount,
dataType: "xml",
success: function(xml) {
var artists = $("artist", xml),
i = 0,
c = 0;

function getTracksComplete() {
if (--c === 0)
nextBatch();
}

function nextBatch() {
for(; c < 5 && i < artists.length; i++, c++) {
// artists[i] is the current artist record
// calculate and output some stuff and then call getTracks()
getTracks(artistName, artistNamePOST, artistPlaycount, divId, artistId,
getTracksComplete);
}
}

// Optional - if you need to calculate statistics on all the artists
// then do that here before starting the batches of getTracks calls
artists.each(function() { /* do something */ });

// Kick of the first batch of 5
nextBatch();
}
});

function getTracks(artistName, artistNamePost, artistPlaycount, divId, artistId,
callback){
$.ajax({
type: "POST",
url: "prepXML.php",
data: "method=gettracks&user=" + userName + "&artist=" + artistNamePOST + "&playcount=" + artistPlaycount,
dataType: "xml",
success: function(xml){
// calculate and output some stuff
},
complete : function() {
if (callback) callback();
});
}
});

上面的只是我的头脑(所以我没有时间来构建它来缩放或绘制它),但我的想法是,而不是使用 .each() 要一次遍历所有艺术家,我们将缓存 jQuery 对象并一次执行几个。调用函数 nextBatch()(它是成功处理程序的本地函数,因此可以访问局部变量)将运行一个只调用 getTracks() 5 次的循环,但从上次中断的地方开始处理。同时,getTracks() 已略微更新以接受回调函数,因此当 its ajax 调用完成时(请注意,我们在完成时执行此操作,而不是在出现错误时执行此操作)可以让主进程知道它已经完成了。在回调中,我们跟踪有多少已完成以及它们何时再次调用 nextBatch()

关于javascript - 我怎样才能对 jQuery AJAX 查询进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8602603/

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