views:

181

answers:

2

I use $.(ajax) function extensively in my app to call ASP.net web services. I would like to write a wrapper in order to centralize all the ajax calls. I found few simple solutions, but none address an issue of passing parameters to delegates, for example, if i have:

$.ajax({
        type: "POST",
          url: "http://localhost/TemplateWebService/TemplateWebService/Service.asmx/GetFoobar",

        data: jsonText,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            var results = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;

            OnSuccess(results, someOtherParam1, someOtherParam2);


        },

        error: function(xhr, status, error) {
            OnError();
        }
    });

The wrapper to this call would have to have the way to pass someOtherParam1, someOtherParam2 to the OnSuccess delegate...Aside from packing the variables into a generic array, I can't think of other solutions.

How did you guys address this issue?

A: 

I had the same issue. My way around it was to include the parameter in the data variable and then pull it out of this.data on success/error/complete. this.data will look like foo=1&bar=2&baz=3 when it comes back so you will need to parse the parameters out.

$.ajax({
  url: 'blah.html',
  data: {foo:1,someOtherParam1:2,someOtherParam2:3},
  success: function(data) {
    var params = this.data.split("&");
    OnSuccess(results, params[1].split("=")[1], params[2].split("=")[1]);
  }
});

Make sure you don't get this.data confused with the data variable that is returned with the success function...

Bradley Mountford
what if you have several parameters? do you have something like this.data.param1, this.data.param2, etc...?
gnomixa
Bradley Mountford