Javascript 如何在AJAX调用的回调中访问正确的'this'?
我无法在回调函数中访问Javascript 如何在AJAX调用的回调中访问正确的'this'?,javascript,ajax,Javascript,Ajax,我无法在回调函数中访问this,但我最终使用this指向AJAX对象,而不是调用onClickEmail函数的this对象。我尝试在变量中获取引用,但也没有多大帮助 我在这里做错了什么: onClickEmail() { var that = this; var hey = "xyz" $.ajax({ url: 'http://rest.learncode.academy/api/test123/tweets' }).then(function(response) {
this
,但我最终使用this
指向AJAX对象,而不是调用onClickEmail
函数的this
对象。我尝试在变量中获取引用,但也没有多大帮助
我在这里做错了什么:
onClickEmail() {
var that = this;
var hey = "xyz"
$.ajax({
url: 'http://rest.learncode.academy/api/test123/tweets'
}).then(function(response) {
console.log(hey);
console.log(that);
});
}
除了解决这个问题,我还想知道为什么我可以读取hey
变量的值,但是未定义这个-变量指拥有函数的对象。
使用绑定或尝试
var that = this;
onClickEmail(){
$.ajax({
url: 'http://rest.learncode.academy/api/test123/tweets'
}).then(function(response) {
hey = that;
});
}
如果我能理解你想用“this”做什么,我可能会有更多的帮助。我正在使用emberjs创建一个web应用程序。单击DOM元素时会调用此方法onClickEmail
。拥有此“onClickEmail”方法的类有一些属性,我需要在收到AJAX响应后立即访问这些属性。当我尝试访问“未捕获引用错误:未定义”错误时,很难说没有完整的代码。你想在“that”中放什么?下面是完整的代码:你想从“this”变量中得到什么?模型DOM元素?您可以获取此模型。获取('model')或在{{{email list email=emailUnit onClickEmail=(action“onClickEmail”emailUnit)}中发送参数add model,并在控制器onClickEmail:function(email)中添加参数