2015-11-02 109 views
0

我的文件js有一個問題,它調用了多個http請求。 我有一個按鈕,調用該函數VisualizzaReport這是在我的文件visualizzaReport.js同一個js文件發出的多個http請求

下面是函數VisualizzaReport(選擇是用戶的ID)

function visualizzaReport(select){ 
     reportUtente(select) 
     loadPianificazione(select) 
    } 

這裏的功能reportUtente(選擇)

function reportUtente(select) { 
     var url = "../loadReportUtenteServlet?"; 
     url += "type=perso_atti&value=" + select.value; 
     xmlhttp.onreadystatechange = handlerForReportUtente; 
     xmlhttp.open("GET", url); 
     xmlhttp.send(""); 

    } 

在這裏,函數loadPianificazione(選擇)

function loadPianificazione(select) { 
     var url = "../loadPianificazione2Servlet?"; 
     url += "type=pianificazioni&value=" + select.value; 
     xmlhttp.onreadystatechange = handlerForPianificazioneUtente; 
     xmlhttp.open("GET", url); 
     xmlhttp.send(""); 
    } 

我的問題是,功能reportUtente啓動,但沒有效果,因爲它似乎是由loadPianificazione函數替代。 只有當reportUtente完成執行時,我如何才能調用loadPianificazione?

回答

0

在你的情況,我建議您使用jQuery的AngularJs這個目的。

jQuery的例如:

$.get('url1.com', function(){ 
    $.get('url2.com'); 
}) 

你會要求url2.com只有當第一個請求已完成。

0

您似乎在使用單個全局變量xmlhttp

然後你調用兩個函數來處理它。第二個將在第一個請求完成之前覆蓋xmlhttp.onreadystatechange,因此您放入的第二個函數將針對每個請求調用。

不要這樣做。爲每個請求創建一個新的XMLHttpRequest實例,並將其保留在本地範圍內,以免干擾其他實例。

function reportUtente(select) { 
    var url = "../loadReportUtenteServlet?"; 
    url += "type=perso_atti&value=" + select.value; 

    var xmlhttp = new XMLHttpRequest(); // New instance here 

    xmlhttp.onreadystatechange = handlerForReportUtente; 
    xmlhttp.open("GET", url); 
    xmlhttp.send(""); 

} 

您還沒有共享handlerForReportUtente,但它應該是這個樣子:

function handlerForReportUtente() { 
    alert(this.responseText); // Use `this` to get the right XHR object 
}