Javascript 如何让jQuery将自定义参数传递给异步AJAX回调函数?
我的页面处理许多“存储”对象,每个对象都有一个名为“数据”的字段。然而,这些数据是通过AJAX请求获取的,这可能是并行的Javascript 如何让jQuery将自定义参数传递给异步AJAX回调函数?,javascript,jquery,ajax,Javascript,Jquery,Ajax,我的页面处理许多“存储”对象,每个对象都有一个名为“数据”的字段。然而,这些数据是通过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,st
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,即使它们具有相同的查询参数
有没有其他方法可以实现我想要的功能?功能存储(id){
this.id=id;
this.queryparam='blah';
this.items=null;
}
您应该能够使用闭包:
var tmp = this;
$.get("/get_items",{q:this.quaryparam},function(data,status){
tmp.data = data;
});
这就是你的意思吗?似乎起作用了,尽管我不明白如何在匿名函数中访问变量“tmp”。:-)
谢谢马克和里卡多 我写了这个插件,我认为它会很有用
闭包就是这样做的。谷歌的“闭包”和“词法范围”——这些都是JavaScript中需要理解的重要概念。
var tmp = this;
$.get("/get_items",{q:this.quaryparam},function(data,status){
tmp.data = data;
});