[英]Passing extra arguments to XMLHttpRequest.onload
我正在嘗試在javascript中使用XMLHttpRequest與服務器通信。
如何將信息傳遞給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傳遞到處理函數? (不使用全局變量)
只需以這種方式使用閉包即可:
...
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);
};
};
公認的解決方案對我不起作用,但是確實可以
const params = new FormData();
params.append('selectedValue', selectedValue);
const xhr = new XMLHttpRequest();
xhr.open('post', url, true);
xhr.send(params);
xhr.extraInfo = extraInfo; // <- set your data here
xhr.onload = (e) => {
const data = JSON.parse(xhr.responseText);
alert(xhr.extraInfo) /// <- access it like this
alert(e.target.extraInfo) // <- or like this
//return data;
};
我在循環中使用了您的代碼,但是出現了一個問題,因為extraINof
返回的值始終相同! 我認為循環中的最后一個值。
代替xhr.extraInfo
使用extraInfo
。
我發現可以通過以下方式將額外的信息傳遞到請求處理程序中:(至少對我有好處)
request.open(...);
request.extraInfo = identifier;
request.onload = function() {
identifier = this.extraInfo;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.