Tir*_*esi 5 javascript xmlhttprequest
我正在尝试与服务器通信,在 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);
};
Run Code Online (Sandbox Code Playgroud)
如何将参数 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);
};
};
Run Code Online (Sandbox Code Playgroud)
小智 5
我发现可以通过这种方式将额外信息传递给请求处理程序:(至少对我有好处)
request.open(...);
request.extraInfo = identifier;
request.onload = function() {
identifier = this.extraInfo;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4825 次 |
| 最近记录: |