[英]How to push parent object from jQuery.ajax success statement
我有一個包含子功能和對象的功能:
//API load function
var apiDataLoader = function () {
// Set default settings
this.apiSeason = '7924';
this.apiMatchDay = '30';
this.apiType = 'gamelist';
this.apiLink = 'http://example.com/';
this.apiLinkData = {
app: this.apiType,
season_num: this.apiSeason,
match_day: this.apiMatchDay
}
this.apiData = new Object;
//load API
apiDataLoader.prototype.load = function() {
$.ajax({
url: this.apiLink,
data: this.apiLinkData,
success: function(data) {
apiDataLoader.apiData = data; //this is not working
// I need to push somehow responce data to 'apiDataLoader.apiData' object
}
});
}
}
如您在我的代碼中看到的,我試圖將$.ajax
響應推送到名為apidataLoader.apiData
父函數對象元素,但是我無法實現。
有任何想法嗎?
PS: data
值中的響應是JSON
對象。
嘗試這個:
apiDataLoader.prototype.load = function() {
var self = this; //Store the current object to avoid `this` problem in javascript.
$.ajax({
url: this.apiLink,
data: this.apiLinkData,
success: function(data) {
self.apiData = data; //assign value
}
});
}
由於load()
是在apiDataLoader
的原型上定義的,因此在apiDataLoader
時它將接收apiDataLoader
的實例作為上下文,換句話說, load()
內部的this
關鍵字將指向在其上調用apiDataLoader
的實例,因此您需要將代碼更改為以下代碼:
apiDataLoader.prototype.load = function() {
var that = this; // this is the instance of apiDataLoader on which this method is called
$.ajax({
url: this.apiLink,
data: this.apiLinkData,
success: function(data) {
that.apiData = data; //assign value
}
});
}
您需要引用apiData
使用當前對象的屬性this
,但是你需要緩存它的外面$.ajax
成功處理程序的范圍this
在功能會有所不同。 嘗試這個:
apiDataLoader.prototype.load = function() {
var _this = this;
$.ajax({
url: this.apiLink,
data: this.apiLinkData,
success: function(data) {
_this.apiData = data;
}
});
}
現在,您正在構造函數apiDataLoader
上創建一個新屬性,而不是當前實例。 這是一種實現方法:
$.ajax({
url: this.apiLink,
data: this.apiLinkData,
dataType: 'json', //will automatically parse the response as JSON
success: function(data) {
this.apiData = data;
},
context: this //sets the context object to the current instance in the callback
});
另外,請注意,原型函數應在構造函數外部聲明,否則使用原型沒有優勢,因為為每個新創建的實例都重新聲明了這些函數。 此外,構造函數以大寫字母開頭,這是JS中的約定,您應該遵循它。
function ApiDataLoader() {
//...
}
ApiDataLoader.prototype = {
constructor: ApiDataLoader,
load: function () {
//...
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.