I want to assign value to a class instance variable from within ajax success functions, code will explain better what I mean.
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
};
});
};
};
If I try this.response, it obviously doesn't work. If I assign this to some variable before I make ajax call, It doesn't work either. I mean this:
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
};
});
};
};
I'll appreciate your help!!!
Since AJAX is asynchronous, you can't use someVariable.response
until after the AJAX call completes. The appropriate way is to have someMethod
take a callback:
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();
};
});
};
};
Then you would use it like this:
var someVariable = new someClass;
someVariable.someMethod(function() {
console.log(someVariable.response);
});
While @Barmar solution will work, i think the best way its to just use promises.. and since you are using jQuery already this is pretty easy. See below:
var SomeClass = function() { this.someMethod = function() { return $.ajax({ method: 'GET', url: 'http://example.com' }); }; };
And then you do something like this:
var someVariable = new SomeClass();
someVariable.someMethod().then(function(returnedValue){
console.log(JSON.parse(returnedValue));
});
I believe that promises is the way to go and since they will be included in ES6... its better to familiarise yourself with the concept.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.