1

如果您正在动态创建 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");
}
4

1 回答 1

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); })
}
于 2013-06-20T10:07:09.053 回答