$.(ajax) wrapper for Jquery - passing parameters to delegates

北城余情 提交于 2019-12-24 10:19:42

问题


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?


回答1:


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...



来源:https://stackoverflow.com/questions/2836037/ajax-wrapper-for-jquery-passing-parameters-to-delegates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!