[英]How do i assign value to instance variable within ajax success function
我想從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是異步的, someVariable.response
直到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);
});
雖然@Barmar解決方案可以工作,但我認為最好的方法是僅使用Promise ..並且由於您使用的是jQuery,因此這非常容易。 見下文:
var SomeClass = function() { this.someMethod = function() { return $.ajax({ method: 'GET', url: 'http://example.com' }); }; };
然后您執行以下操作:
var someVariable = new SomeClass();
someVariable.someMethod().then(function(returnedValue){
console.log(JSON.parse(returnedValue));
});
我相信承諾是要走的路,並且因為它們將被包含在ES6中……所以最好讓自己熟悉這個概念。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.