在我的 javascript 文件中,我无法访问 Ajax 成功函数中的脚本级变量。见以下代码:
MyApplication.Test = Class.extend({
...
...
testElement : null,
...
...
updateElementBackground : function(url)
{
if(url.length > 0) {
var response = $.ajax(url ,{
contentType : "application/json",
headers: {"Access-Control-Request-Headers": "X-requested-with"},
type : "GET",
success : function(data) {
this.testElement.css("backgroundImage","url('"+url+data+"')"); // testElement is undefined now. here this refers to the Ajax call
},
error : function(e) {
errorCallback(e);
}
});
}
else
{
this.testElement.css("backgroundImage","testImage.jpg"); // testElement is accessible here
}
}
});
如何在 Ajax 成功函数中获取 "testElement"?
最佳答案
当您尝试获取this.testElement
时,您访问了success
函数的this
。并且没有 testElement
属性。
尝试在 updateElementBackground
范围内预定义 this
。
updateElementBackground : function(url)
{
var that = this;
var response = $.ajax(url ,{
success : function(data) {
that.testElement.css("backgroundImage","url('"+url+data+"')");
},
});
}
关于javascript - 如何在 Ajax 成功函数中获取脚本级变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23929934/