2013-06-20 38 views
1

如果你是動態創建Ajax請求,因爲他們來異步地執行成功回調,你怎麼能知道是由每個回調回應什麼要求?多個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

嘗試下一個:

$.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); }) 
} 
+0

中,.done和.fail回調遭受同樣的問題,因爲是成功的:它們被執行的時候,我的價值發生了變化,所以這種解決方案不起作用。 – Flatline1963

+0

不幸的是我不能改變服務器的行爲,所以我不能讓它回覆我的問題。 – Flatline1963

+0

@ Flatline1963我eddited後加入另一posibility,檢查其是否正常工作:) – maqjav