简体   繁体   English

For 循环中的 JQuery/Ajax 调用

[英]JQuery/Ajax calls in a For Loop

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.我正在尝试使用来自循环 ajax 调用的 JSONP 数据填充 HTML 表,其中 URL 每次都会更改。 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.每次都使用相同的回调函数,但很明显,我不断覆盖要发送到 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.所以,基本上,我可以把所有#p1 的东西放在函数的末尾,但我想把它全部改成 $p2 来填充我表的下一行。 The HTML should be obvious, but here it is... HTML 应该很明显,但这里是...

<body>
<center>
<table width="100%" border="0">
  <tr>
    <td id="p1_classspec">&nbsp;</td>
    <td id="p1_iLevelE">&nbsp;</td>
    <td id="p1_upgrades">&nbsp;</td>
    <td id="p1_cloak">&nbsp;</td>
    <td id="p1_tier">&nbsp;</td>
    <td id="p1_profs">&nbsp;</td>
    <td id="p1_achieve">&nbsp;</td>
    <td id="p1_normalkills">&nbsp;</td>
    <td id="p1_heroickills">&nbsp;</td>
    <td id="p1_xp">&nbsp;</td>
  </tr>
  <tr>
    <td id="p2_classspec">&nbsp;</td>
    <td id="p2_iLevelE">&nbsp;</td>
    <td id="p2_upgrades">&nbsp;</td>
    <td id="p2_cloak">&nbsp;</td>
    <td id="p2_tier">&nbsp;</td>
    <td id="p2_profs">&nbsp;</td>
    <td id="p2_achieve">&nbsp;</td>
    <td id="p2_normalkills">&nbsp;</td>
    <td id="p2_heroickills">&nbsp;</td>
    <td id="p2_xp">&nbsp;</td>
  </tr>
  <tr>
    <td id="p3_classspec">&nbsp;</td>
    <td id="p3_iLevelE">&nbsp;</td>
    <td id="p3_upgrades">&nbsp;</td>
    <td id="p3_cloak">&nbsp;</td>
    <td id="p3_tier">&nbsp;</td>
    <td id="p3_profs">&nbsp;</td>
    <td id="p3_achieve">&nbsp;</td>
    <td id="p3_normalkills">&nbsp;</td>
    <td id="p3_heroickills">&nbsp;</td>
    <td id="p3_xp">&nbsp;</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).如果你点击这个链接,你会看到我要做什么(这不是使用 for 循环)。 I just want to drastically cut down on my code.我只想大幅减少我的代码。

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){
                }
            })
        }

    });

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;它不起作用,因为i最终将成为循环中的最后一个i值; You need something like below你需要像下面这样的东西

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"等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){
        }
    })
}

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

How about creating a #P i first then append to parent.如何先创建一个#P i 然后附加到父级。 Then change the html()?然后更改 html()?

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.我会使用闭包解决方案来迷惑 Java 程序员,我认为它更优雅,更有趣。
http://jsfiddle.net/kmiklas/79s8S/4/ http://jsfiddle.net/kmiklas/79s8S/4/
open console to view data打开控制台查看数据

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.现在,在检索 AJAX 数据时,创建一个立即函数,每次都传递 i。 This will create a new scope for each callback:这将为每个回调创建一个新范围:

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."您也可以使用 Array.prototype.forEach(),“forEach() 方法对每个数组元素执行一次提供的函数。”
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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.我使用 jQuery 进行 AJAX 调用。 I didn't test them;我没有测试它们; you have to fiddle with your data_from_ajax_call variable.你必须摆弄你的data_from_ajax_call变量。 Maybe return a JSON object here.也许在这里返回一个 JSON 对象。

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

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