[英]How to get jQuery to pass custom arguments to asynchronous AJAX callback functions?
我的頁面處理許多“商店”對象,每個對象都有一個名為“數據”的字段。 但是,這些數據是通過AJAX請求獲取的,這些請求可以並行進行。
function Store(id){
this.id = id;
this.queryparam = 'blah';
this.items = null;
}
Store.prototype.fetch = function(){
$.get("/get_items",{q:this.quaryparam},function(data,status){
// how to store the received data in this particular store object? Being
// a callback function, I don't have a reference to this object as 'this'
// this.data = data; //will not work
});
}
在回調函數中,我嘗試為調用對象定義一個默認參數,如下所示:
$.get("/get_items",{q:this.quaryparam},function(data,status, ref = this) ...
但事實證明,javascript不支持這樣的默認參數值。 我可以以某種方式讓jquery在回調函數中傳遞對'this'存儲的引用嗎?
我想到了其他幾種方法,但沒有一種方法可行:
我可以使用同步請求設置商店數據,但那不是AJAX的重點,是嗎?
對我來說另一種方法是,也可以在響應中返回的請求中發送商店ID。 例如:
// in Store.fetch()
$.get("/get_items",{q:this.quaryparam,id:this.id},function(responsetext,status){
var response = eval(responsetext);
stores[response.id].data = response.data;
});
我不喜歡這種方法,因為這會污染響應只是因為客戶端代碼無法跟蹤哪個對象發送了哪個請求。
此外,由於store.id是特定於客戶端的,因此它也會破壞服務器上的緩存。 不同的請求URL將用於兩個不同的存儲,即使它們具有相同的查詢參數。
有沒有其他方法可以實現我想要的?
你應該能夠使用閉包:
var tmp = this;
$.get("/get_items",{q:this.quaryparam},function(data,status){
tmp.data = data;
});
你是這個意思嗎?
function Store(id){this.id = id; this.queryparam ='blah'; this.items = null; }
Store.prototype.fetch = function(){
var that = this;
$.get("/get_items",{q:this.quaryparam},function(response){
that.callback(response)
});
}
Store.prototype.callback = function(response){
// and here you can use
this.items = response // just example
}
似乎工作,雖然我不明白如何在匿名函數內訪問變量'tmp'。 :-)
謝謝Marc和ricardoe!
我寫了這個插件,我覺得它會很有用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.