多个jQuery ajax调用;如何将回调与请​​求相关联?

时间:2013-06-20 10:00:30

标签: jquery

如果您正在动态创建ajax请求,因为它们会异步执行成功回调,您如何知道每个回调响应的请求是什么?

示例:

我有一系列n个问题,服务器给出了答案:

var questions = Array("What's your name?", "What's your mom's name?", "What's your pet's name?");
for (var i=0; i<questions.length; i++) {
            $.get ("server.php", { "Question" : questions[i] },
                    function(data) { 
                        /* I want to process answer, but at this time I cannot access the value of i,
                           so what's question is being answered ? */
                    }, "json");
}

1 个答案:

答案 0 :(得分:1)

尝试下一个:

$.get("server.php", { "Question" : questions[i] },
    function(data) {
        alert("success. The next question is being answered: "+questions[i]);
    }, "json")
    .done(function() { alert("second succes. This question has been answered:" + questions[i]); })
    .fail(function() { alert("Error answering this question: "  +questions[i]); })

您可以在回复中发送正在回答的问题,这样您就可以在数据变量中获得该信息。

工作测试

var questions = Array("What's your name?", "What's your mom's name?", "What's your pet's name?");
for (var i=0; i<questions.length; i++) {
   sendGet(questions[i]);
}

function sendGet(question) {
    $.get("server.php", { "Question" : question },
    function(data) {
        alert("success. The next question is being answered: "+question);
    }, "json")
    .done(function() { alert("second succes. This question has been answered:" + question); })
    .fail(function() { alert("Error answering this question: "  +question); })
}