【问题标题】:How to get jQuery to pass custom arguments to asynchronous AJAX callback functions?如何让 jQuery 将自定义参数传递给异步 AJAX 回调函数?
【发布时间】:2009-01-09 08:12:12
【问题描述】:

我的页面处理许多“存储”对象,每个对象都有一个名为“数据”的字段。但是,这些数据是通过可能并行进行的 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 将用于两个不同的商店,即使它们具有相同的查询参数。

还有其他方法可以实现我想要的吗?

【问题讨论】:

    标签: javascript jquery ajax


    【解决方案1】:

    你应该可以使用闭包:

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

    你是这个意思吗?

    【讨论】:

      【解决方案2】:

      函数存储(id){ 这个.id = id; this.queryparam = '废话'; 这个.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
      }
      

      【讨论】:

        【解决方案3】:

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

        感谢马克和里卡多!

        【讨论】:

        • 这就是闭包的作用。谷歌的“闭包”和“词法范围”——这些是 JavaScript 中需要理解的重要概念。
        【解决方案4】:

        这个插件是我写的,我觉得会有用的

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

        【讨论】:

          猜你喜欢
          • 2011-07-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多