我有一个函数向我的服务器发送一个简单的AJAX请求。浏览器的javascript代码如下所示:
function testRequest() {
var xhr = new XMLHttpRequest();
xhr.onload = () => {
console.log("RESPONSE RECIEVED");
console.log(this); // 'this' should be a XMLHttpRequest object
console.log(this.status);
console.log(this.responseText);
};
xhr.open('POST', `http://server_ip/test`, true);
xhr.send();
}
服务器代码看起来如下(Express.js):
app.post("/test", (req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.status(200).send("testing");
});
当函数被调用时,我在浏览器控制台上得到的响应如下:
RESPONSE RECIEVED
Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
undefined
而不是预期的:
RESPONSE RECIEVED
XMLHttpRequest {…}
200
"testing"
换句话说,浏览器正在接收服务器响应,但是传递给onload函数(this
)的对象似乎是某个“窗口”对象,而不是XMLHttpRequest
对象。因此,没有状态或responseText变量。
在浏览器中检查请求时,响应的主体是基于预期的“测试”。
发布于 2019-08-13 13:23:19
这是因为您使用的是箭头函数() =>
,在这样的函数中,this
是从词汇上捕获的,并且不随上下文而改变。在您的示例中,this
指向的是window
上下文,因为这是封闭的词法作用域,即声明它的位置。
您需要将其更改为普通的function
,以使this
指向xhr
对象:
xhr.onload = function(){
console.log("RESPONSE RECIEVED");
console.log(this); // 'this' should be a XMLHttpRequest object
console.log(this.status);
console.log(this.responseText);
};
来自MDN 文档的
箭头函数没有它自己的这个函数。使用了包围词法作用域的此值;箭头函数遵循正常的变量查找规则。因此,在搜索当前作用域中不存在的内容时,箭头函数最终会从其包围作用域找到该函数。
https://stackoverflow.com/questions/57478631
复制相似问题