gpt4 book ai didi

javascript - 如何在 Ajax 成功函数中获取脚本级变量?

转载 作者:行者123 更新时间:2023-11-30 10:15:36 24 4
gpt4 key购买 nike

在我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com