本文介绍了阿贾克斯不工作在环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要执行阿贾克斯在一个循环接一个地获取数据之一。我做了这样的事情在我的javascript函数。

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?

推荐答案

您正在处理一个通病关闭。通过执行您的Ajax请求的时候,计数器我已经是始终在它的最后的值(4)。

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:

最简单的方式:

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

这篇关于阿贾克斯不工作在环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 20:53