在我的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”?

最佳答案

范围内的问题。尝试像这样在函数中创建一个var。

MyApplication.Test = Class.extend({


...
...

testElement : null,

...
...

updateElementBackground : function(url)
{
    var testElement = this.testElement;
    if(url.length > 0) {
    var response =  $.ajax(url ,{
                 contentType : "application/json",

                 headers: {"Access-Control-Request-Headers": "X-requested-with"},
                 type : "GET",
                 success : function(data) {
                      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
              }
}
});

关于javascript - 如何在Ajax成功函数中获取脚本级变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23929934/

10-11 13:00