2016-12-28 174 views
1

我試圖與服務器comunicate,使用JavaScript中的XMLHttpRequest。傳遞額外的參數給XMLHttpRequest.onload

如何傳遞到onload事件功能的信息?

// global variable that containts server response 
var reply; 

var makeRequest = function(extraInfo) { 
    var request = new XMLHttpRequest(); 
    request.open(...); 
    request.onload = handler; 
}; 

var handler = function(data) { 
    reply = data.target.response; 
    console.log("Server Reply: " + reply); 
}; 

如何將參數extraInfo從makeRequest傳遞到處理函數? (不使用全局變量)

回答

2

只需使用一個封閉在這樣的方式:

... 
var makeRequest = function(extraInfo) { 
    var request = new XMLHttpRequest(); 
    request.open(...); 
    request.onload = function(data) { 
     // extraInfo is accessible here 
     reply = data.target.response; 
     console.log("Server Reply: " + reply); 
    }; 
};