我想从ajax成功函数中为类实例变量赋值,代码会更好地解释我的意思。
var SomeClass = function() {
this.someMethod = function() {
$.ajax({
method: 'GET',
url: 'http://example.com',
success: function(resp) {
var js = JSON.parse(resp);
// I want to assign js object to SomeClass.response instance variable
};
});
};
};
如果我尝试 this.response,它显然不起作用。如果我在进行 ajax 调用之前将其分配给某个变量,它也不起作用。我的意思是:
var SomeClass = function() {
this.someMethod = function() {
// Asign this to self
var self = this;
$.ajax({
method: 'GET',
url: 'http://example.com',
success: function(resp) {
var js = JSON.parse(resp);
// I want to assign js object to SomeClass.response instance variable
self.response = js; // However it doesn't work
};
});
};
};
非常感谢您的帮助!
最佳答案
由于 AJAX 是异步的,因此在 AJAX 调用完成之前您无法使用 someVariable.response
。适当的方法是让 someMethod
进行回调:
var SomeClass = function() {
this.someMethod = function(callback) {
// Asign this to self
var self = this;
$.ajax({
method: 'GET',
url: 'http://example.com',
success: function(resp) {
var js = JSON.parse(resp);
// I want to assign js object to SomeClass.response instance variable
self.response = js;
callback();
};
});
};
};
然后你会像这样使用它:
var someVariable = new someClass;
someVariable.someMethod(function() {
console.log(someVariable.response);
});
关于javascript - 如何在ajax成功函数中为实例变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26323886/