简体   繁体   中英

How to get jQuery to pass custom arguments to asynchronous AJAX callback functions?

My page deals with many "Store" objects, each of them has a field called 'data'. However, this data is fetched via AJAX requests which may be parallely going on.

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
    });
}

In the callback function I tried defining a default parameter to the calling objects as following:

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

But turns out that javascript does not support default argument values like this. Can I somehow get jquery to pass a reference to 'this' store in the callback function?

I thought of a couple of other approaches but none of them work:

I could set the store data using synchronous requests but then thats not the point of AJAX, is it?

Another way for me could be, to send the store id also in the requests which will come back in the response. For eg:

// 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;
});

I do not like this approach because this pollutes the response just because the client-side code was unable to keep track of which request was sent by which object.

Moreover, since store.id is client-specific, it will also mess up caching at the server. A different request URL will be used for two different stores even though they have the same query parameters.

Is there any other way to achieve what I want?

You should be able to use closure:

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

Is that what you mean?

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
}

Seems to be working, although I don't understand how the variable 'tmp' is accessible inside the anonymous function. :-)

Thanks Marc and ricardoe !

I wrote this plugin, I think it will be useful

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM