如何让jQuery将自定义参数传递给异步AJAX回调函数?

时间:2009-01-09 08:12:13

标签: 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,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将用于两个不同的存储,即使它们具有相同的查询参数。

还有其他方法可以实现我的目标吗?

4 个答案:

答案 0 :(得分:5)

你应该可以使用闭包:

var tmp = this;
$.get("/get_items",{q:this.quaryparam},function(data,status){
    tmp.data = data;
});

这是你的意思吗?

答案 1 :(得分:2)

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
}

答案 2 :(得分:0)

似乎工作正常,虽然我不明白在匿名函数中如何访问变量'tmp'。 : - )

感谢Marc和ricardoe!

答案 3 :(得分:0)

我写了这个插件,我觉得它很有用

http://code.google.com/p/jquerycallback/