javascript For 循环中的 JQuery/Ajax 调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21373643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery/Ajax calls in a For Loop
提问by Bonedancer
Is it possible to put ("xxxxx").html(data)
in a for loop where the "xxxx" variable changes each time?
是否可以放入("xxxxx").html(data)
一个“xxxx”变量每次都改变的 for 循环?
I honestly feel like I've tried everything. I'm trying to fill up an HTML table with JSONP data from a looping ajax call where the URL changes each time. The same callback function is used every time, but, obviously, I keep overwriting the data that is to be sent to the HTML table tags because I can't figure out a way to dynamically change these variables.
老实说,我觉得我已经尝试了一切。我正在尝试使用来自循环 ajax 调用的 JSONP 数据填充 HTML 表,其中 URL 每次都会更改。每次都使用相同的回调函数,但很明显,我一直覆盖要发送到 HTML 表格标记的数据,因为我无法找到动态更改这些变量的方法。
Basically, I want the first time the callback function is called to store data in something like...
基本上,我希望第一次调用回调函数以将数据存储在类似...
$("#p1_points").html(data_from_ajax_call)
The second time I want it to do...
第二次我想要它做...
$("#p2_points").html(data_from_ajax_call)
I've tried silly things like (inside a for loop) doing ...
我尝试过一些愚蠢的事情,比如(在 for 循环中)做......
$("#p" + i + "_points").html(data_from_ajax_call)
and all sorts of fun stuff, but it doesn't accept arguments of any kind... So, any thoughts? Is this trivial and I'm just over-thinking and under-sleeping it?
和各种有趣的东西,但它不接受任何形式的论点......那么,有什么想法吗?这是微不足道的,我只是过度思考和睡眠不足吗?
Thanks in advance for any help.
在此先感谢您的帮助。
UPDATING FOR CLARITY
更新清晰
My ajax calls look like this...
我的 ajax 调用看起来像这样......
for (var i = 0; i < thisweeksraiders.length; i++){
$.ajax({
"url":"http://us.battle.net/api/wow/character/aerie-peak/" + thisweeksraiders[i] + "?jsonp=myCallback",
"type":"GET",
"data": { fields: "items, professions, talents, progression"},
"dataType":"jsonp",
"contentType":"application/json",
"jsonpCallback":"myCallback",
"success":function(data1){
}
})
}
and my callback function looks like this...
我的回调函数看起来像这样......
function myCallback(data1) {
//itemscounter += 1;
var hascloak = "No";
var possupgrades = 30;
var offhandequipped = false;
var tempupgrades = 0;
var tierequipped = 0;
for (var i = 0; i < gearlist.length; i++){
if (data1.items[(gearlist[i])].tooltipParams.upgrade)
tempupgrades += data1.items[(gearlist[i])].tooltipParams.upgrade.current;
}
for (var i = 0; i < tierlist.length; i++){
if(data1.items[(tierlist[i])].tooltipParams.set)
tierequipped += 1;
}
if (data1.items.offHand){
tempupgrades += data1.items.offHand.tooltipParams.upgrade.current;
offhandequipped = true;
}
if (offhandequipped)
possupgrades = 32;
if(data1.items[(gearlist[3])].quality == 5)
hascloak = "Yes";
$("#p1_cloak").html(hascloak);
$("#p1_tier").html(tierequipped + "/5");
$("#p1_achieve").html(data1.achievementPoints);
$("#p1_iLevelE").html(data1.items.averageItemLevelEquipped);
$("#p1_upgrades").html(tempupgrades + "/" + possupgrades);
var totalnormalkills = 0;
var totalheroickills = 0;
var furthestboss = null;
for (var i = 0; i < soobosslist.length; i++){
totalnormalkills += data1.progression.raids[31].bosses[i].normalKills;
totalheroickills += data1.progression.raids[31].bosses[i].heroicKills;
}
if (totalheroickills == 0){
for (var i = 14; i > 0; i--){
if (data1.progression.raids[31].bosses[i-1].normalKills > 0){
furthestboss = i + "N";
break;
}
}
}
else {
for (var i = 14; i > 0; i--){
if (data1.progression.raids[31].bosses[i-1].heroicKills > 0){
furthestboss = i + "H";
break;
}
}
}
$("#p1_normalkills").html(totalnormalkills);
$("#p1_heroickills").html(totalheroickills);
$("#p1_xp").html(furthestboss);
var classtemp;
var colortemp;
switch(data1.class){
case 1: classtemp = "Warrior"; colortemp = "#C79C6E"; break;
case 2: classtemp = "Paladin"; colortemp = "#F58CBA"; break;
case 3: classtemp = "Hunter"; colortemp = "#ABD473"; break;
case 4: classtemp = "Rogue"; colortemp = "#FFF569"; break;
case 5: classtemp = "Priest"; colortemp = "#FFFFFF"; break;
case 6: classtemp = "Death Knight"; colortemp = "#C41F3B"; break;
case 7: classtemp = "Shaman"; colortemp = "#0070DE"; break;
case 8: classtemp = "Mage"; colortemp = "#69CCF0"; break;
case 9: classtemp = "Warlock"; colortemp = "#9482C9"; break;
case 10: classtemp = "Monk"; colortemp = "#00FF96"; break;
case 11: classtemp = "Druid"; colortemp = "#FF7D0A"; break;
}
$("#p1_classspec").html("<font color=" + colortemp + "><b>" + data1.name + "</b></font><font size='-1' color=" + colortemp + "><em> (" + data1.talents[0].spec.name + ")</em></font>");
var profstemp = (data1.professions.primary[0].name + " & " + data1.professions.primary[1].name);
$("#p1_profs").html(profstemp);
}
So, basically, all the #p1 stuff I could put at the end of the function, but I'd like to change it all to $p2 to fill in the next row on my table. The HTML should be obvious, but here it is...
所以,基本上,我可以把所有#p1 的东西放在函数的末尾,但我想把它全部改成 $p2 来填充我表的下一行。HTML 应该很明显,但这里是...
<body>
<center>
<table width="100%" border="0">
<tr>
<td id="p1_classspec"> </td>
<td id="p1_iLevelE"> </td>
<td id="p1_upgrades"> </td>
<td id="p1_cloak"> </td>
<td id="p1_tier"> </td>
<td id="p1_profs"> </td>
<td id="p1_achieve"> </td>
<td id="p1_normalkills"> </td>
<td id="p1_heroickills"> </td>
<td id="p1_xp"> </td>
</tr>
<tr>
<td id="p2_classspec"> </td>
<td id="p2_iLevelE"> </td>
<td id="p2_upgrades"> </td>
<td id="p2_cloak"> </td>
<td id="p2_tier"> </td>
<td id="p2_profs"> </td>
<td id="p2_achieve"> </td>
<td id="p2_normalkills"> </td>
<td id="p2_heroickills"> </td>
<td id="p2_xp"> </td>
</tr>
<tr>
<td id="p3_classspec"> </td>
<td id="p3_iLevelE"> </td>
<td id="p3_upgrades"> </td>
<td id="p3_cloak"> </td>
<td id="p3_tier"> </td>
<td id="p3_profs"> </td>
<td id="p3_achieve"> </td>
<td id="p3_normalkills"> </td>
<td id="p3_heroickills"> </td>
<td id="p3_xp"> </td>
</tr>
</table>
</center>
</body>
If you follow this link, you'll see what I'm going for (this is not using the for loop). I just want to drastically cut down on my code.
如果你点击这个链接,你会看到我要做什么(这不是使用 for 循环)。我只想大幅减少我的代码。
http://www.mynextbit.com/Pages/Wreckedified/test2.html
http://www.mynextbit.com/Pages/Wreckedified/test2.html
One more Update for Patrick...
帕特里克的又一更新……
$(document).ready(function(){
for (var i = 0; i < thisweeksraiders.length; i++){
(function(index)
window.jsonpCallbacks["myCallback" + index] = function(data){
myCallback(data,index);
};
})(i);
$.ajax({
"url":"http://us.battle.net/api/wow/character/aerie-peak/" + thisweeksraiders[i] + "?jsonp=jsonpCallbacks.myCallback" + i,
"type":"GET",
"data": { fields: "items, professions, talents, progression"},
"dataType":"jsonp",
"contentType":"application/json",
"jsonpCallback":"jsonpCallbacks.myCallback"+i,
"success":function(data1){
}
})
}
});
回答by Patrick Evans
if you loop looks something like this:
如果你循环看起来像这样:
for(var i=0; i<10; i++){
$.ajax({
//
success:function(data){
$("#p" + i + "_points").html(data);
}
});
}
it will not work as i
will end up being the last i
value in the loop; You need something like below
它不会工作,因为i
最终会i
成为循环中的最后一个值;你需要像下面这样的东西
for(var i=0; i<10; i++){
(function(index){
$.ajax({
//
success:function(data){
$("#p" + index + "_points").html(data);
}
});
})(i);
}
The closure along with the passing of i
will keep number value for that call.
关闭以及传递i
将保留该调用的数值。
of course there will need to exist elements with ids 1-10 or whatever number you use so:
当然,需要存在 ID 为 1-10 或您使用的任何数字的元素:
<element id="p1_points">
<element id="p2_points">
<element id="p3_points">
...
EDIT to account for JSONP callback:
编辑以考虑 JSONP 回调:
modify myCallback() to be:
将 myCallback() 修改为:
function myCallback(data,index)
and use the index to make your "#p"+index+"_points"
etc ids
并使用索引来制作您的"#p"+index+"_points"
etc id
and then for the loop and ajax:
然后对于循环和ajax:
//Keeps track of the callbacks
//we will prepend 'jsonpCallbacks.' to the callback names
window.jsonpCallbacks = {};
for (var i = 0; i < thisweeksraiders.length; i++){
(function(index){
window.jsonpCallbacks["myCallback"+index] = function(data){
myCallback(data,index);
};
})(i);
$.ajax({
"url":"http://us.battle.net/api/wow/character/aerie-peak/" + thisweeksraiders[i] + "?jsonp=jsonpCallbacks.myCallback"+i,
"type":"GET",
"data": { fields: "items, professions, talents, progression"},
"dataType":"jsonp",
"contentType":"application/json",
"jsonpCallback":"jsonpCallbacks.myCallback"+i,
"success":function(data1){
}
})
}
回答by loxxy
You should have a different callback each time, if you wish to target different entities.
如果您希望针对不同的实体,则每次都应该有不同的回调。
Checkout closures, when you are ready, until then try it this way: (Pseudo code)
Checkout闭包,当你准备好了,直到那时试试这样:(伪代码)
for(...) {
loadData(i);
}
function loadData(i) {
var index = i;
$.ajax({
url: "",
success : function() {
$("#p" + index + "_points").html(data_from_ajax_call);
}
});
}
回答by kmiklas
Well, you have at least two options: use a closure, or use forEach().
好吧,您至少有两个选择:使用闭包,或使用 forEach()。
Fiddle below, containing both. I would use the closure solution, to confuse the Java programmers, and I think that it's more elegant, and more fun.
http://jsfiddle.net/kmiklas/79s8S/4/
open console to view data
小提琴下面,包含两者。我会使用闭包解决方案来迷惑 Java 程序员,我认为它更优雅,更有趣。
http://jsfiddle.net/kmiklas/79s8S/4/
打开控制台查看数据
First, set the id of each row sequentially, like so:
首先,依次设置每一行的 id,如下所示:
<tr id="row1"></tr>
<tr id="row2"></tr>
...
<tr id="rowN"></tr>
Then put your row id's into an array.
然后将您的行 ID 放入一个数组中。
var pointsArray = new Array(999); // whatever length here
for (var i = pointsArray.length; i > -1; i--) {
pointsArray[i] = 'row' + i;
}
CLOSURE SOLUTION:
关闭解决方案:
Now, when retrieving your AJAX data, create an immediate function, passing i every time. This will create a new scope for each callback:
现在,在检索 AJAX 数据时,创建一个立即函数,每次都传递 i。这将为每个回调创建一个新范围:
for (var i = pointsArray.length; i > -1; i--) {
(function(j){
$.ajax({
type: "POST",
url: "some.php",
})
.done(function( data_from_ajax_call ) {
$('#' + pointsArray[j]).html(data_from_ajax_call)
});
})(i);
}
forEach() SOLUTION:
forEach() 解决方案:
You may also use Array.prototype.forEach(), "The forEach() method executes a provided function once per array element."
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
您也可以使用 Array.prototype.forEach(),“forEach() 方法对每个数组元素执行一次提供的函数。”
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
pointsArray.forEach(function(rowName) {
$.ajax({
type: "POST",
url: "some.php",
})
.done(function( data_from_ajax_call ) {
$('#' + rowName).html(data_from_ajax_call)
});
}
I'm using jQuery for the AJAX calls. I didn't test them; you have to fiddle with your data_from_ajax_call
variable. Maybe return a JSON object here.
我使用 jQuery 进行 AJAX 调用。我没有测试它们;你必须摆弄你的data_from_ajax_call
变量。也许在这里返回一个 JSON 对象。
回答by robert.dejesica
How about creating a #P i first then append to parent. Then change the html()?
如何先创建一个#P i 然后附加到父级。然后更改 html()?