JQuery / Ajax在For循环中调用

时间:2014-01-27 05:30:31

标签: javascript jquery ajax

高级程序员,

是否可以将(“xxxxx”)。html(数据)放在for循环中,其中“xxxx”变量每次都会改变?

老实说,我觉得我已经尝试了一切。我正在尝试用循环ajax调用中的JSONP数据填充HTML表,其中URL每次都会更改。每次都使用相同的回调函数,但显然,我会覆盖要发送到HTML表标签的数据,因为我无法找到动态更改这些变量的方法。

基本上,我希望第一次调用回调函数来存储数据...

$("#p1_points").html(data_from_ajax_call)

我第二次想要它......

$("#p2_points").html(data_from_ajax_call)

我尝试过愚蠢的事情(在for循环中)做...

$("#p" + i + "_points").html(data_from_ajax_call)

和各种有趣的东西,但它不接受任何形式的论点......所以,任何想法?这是微不足道的,我只是过度思考并且睡不着觉?

提前感谢您的帮助。

更新CLARITY

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

我的回调函数看起来像这样......

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

所以,基本上,我可以把所有#p1的东西放在函数的末尾,但是我想把它全部更改为$ p2来填充我桌子上的下一行。 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>

如果你按照这个链接,你会看到我想要的东西(这不是使用for循环)。我只想彻底减少我的代码。

http://www.mynextbit.com/Pages/Wreckedified/test2.html

帕特里克的另一个更新......

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

    });

4 个答案:

答案 0 :(得分:10)

如果循环看起来像这样:

for(var i=0; i<10; i++){
   $.ajax({
    //
    success:function(data){
       $("#p" + i + "_points").html(data);
    }
   });
}

它将无效,因为i最终将成为循环中的最后一个i值;你需要类似下面的东西

for(var i=0; i<10; i++){
   (function(index){
      $.ajax({
       //
       success:function(data){
          $("#p" + index + "_points").html(data);
       }
      });
   })(i);
}

关闭以及i的传递将保持该呼叫的数字值。

当然需要存在带有1-10的元素或者你使用的任何数字:

<element id="p1_points">
<element id="p2_points">
<element id="p3_points">
...

编辑以解释JSONP回调:

将myCallback()修改为:

function myCallback(data,index)

并使用索引制作"#p"+index+"_points"等ids

然后是循环和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){
        }
    })
}

答案 1 :(得分:2)

如果您希望定位不同的实体,则每次都应该有不同的回调。

Checkout closures,当你准备好了,直到那时尝试这样:(伪代码)

for(...) {
    loadData(i);
}


function loadData(i) {   
   var index = i; 

   $.ajax({
        url: "",
        success : function() {    
               $("#p" + index + "_points").html(data_from_ajax_call);
        }
   });
}

答案 2 :(得分:0)

如何首先创建#P i然后附加到父级。然后更改html()?

答案 3 :(得分:0)

嗯,你至少有两个选择:使用闭包,或使用forEach()。

下面的小提琴,包含两者。我会使用闭包解决方案来混淆Java程序员,我认为它更优雅,更有趣。
http://jsfiddle.net/kmiklas/79s8S/4/
打开控制台以查看数据

首先,按顺序设置每一行的id,如下所示:

<tr id="row1"></tr>
<tr id="row2"></tr>
...
<tr id="rowN"></tr>

然后将你的行ID放入数组中。

var pointsArray = new Array(999); // whatever length here
for (var i = pointsArray.length; i > -1; i--) {
    pointsArray[i] = 'row' + i;
}

关闭解决方案:

现在,在检索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()解决方案:

您也可以使用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)
     });
}

我正在使用jQuery进行AJAX调用。我没有测试它们;你必须摆弄你的data_from_ajax_call变量。也许在这里返回一个JSON对象。