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