doushu2699 2013-02-26 14:37
浏览 39
已采纳

Ajax无法在循环中工作[重复]

This question already has an answer here:

I want to execute Ajax in a loop to fetch data one by one. I did something like this in my javascript function.

var resultType = $("input[name='resultType']:checked").val();
var finalResult = "";
var loadingMessage = "<img src=\"./results/loader.gif\" alt=\"Loading...\"/><br/>This may take several minutes...";
var htmlMessage=loadingMessage;

$("#result").html(htmlMessage);

for(var i=1;i<5;i++){
    $.ajax({
        type: "GET",
        url: "results/result_html.php?usn="+i+"&resultType="+resultType,
        dataType:"JSON",
        success:function(result){
            finalResult+=result;
            result=result+htmlMessage;
            $("#info").hide();
            $("#result").html(result);              
            $("#usn").attr("placeholder", "Class USN");
        }
    });
}

But it is not executing as I expected. If I remove for loop and give value directly then everything is proper. I'm not much familiar with Ajax. Please can anyone help me?

</div>
  • 写回答

2条回答 默认 最新

  • douci1677 2013-02-26 14:42
    关注

    you are dealing with a common problem with closures. by the time your ajax request is executed, the counter "i" is already and always at it's last value (4).

    you have to create a new scope for that counter, so that it doesn't happen; you can do it in two ways:

    the easy way:

    for(var i=1;i<5;i++){
        var counter = i;
        $.ajax({
            type: "GET",
            url: "results/result_html.php?usn="+counter+"&resultType="+resultType,
            dataType:"JSON",
            success:function(result){
                finalResult+=result;
                result=result+htmlMessage;
                $("#info").hide();
                $("#result").html(result);              
                $("#usn").attr("placeholder", "Class USN");
            }
        });
    }
    

    or the correct way:

    for(var i=1;i<5;i++){
    (function(counter){
        $.ajax({
            type: "GET",
            url: "results/result_html.php?usn="+"counter"+"&resultType="+resultType,
            dataType:"JSON",
            success:function(result){
                finalResult+=result;
                result=result+htmlMessage;
                $("#info").hide();
                $("#result").html(result);              
                $("#usn").attr("placeholder", "Class USN");
            }
        });
    })(i);}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分