开发者

Global AJAX Success handler that inspects JSON data

开发者 https://www.devze.com 2023-04-11 13:56 出处:网络
All my REST services return some common flags as part of every JSON response structure. For example, a notifications flag.How can I cleanly setup something to hook into every ajax request made on the

All my REST services return some common flags as part of every JSON response structure. For example, a notifications flag. How can I cleanly setup something to hook into every ajax request made on the page to check the response payload for the presence of these flags.

I'd also lik开发者_JAVA百科e to do something similar on the request, by having something auto add certain common parameters to the URL prior to the call.

Help please!


It sounds to me like .ajaxSuccess() doc here would let you do what you want as it is a centralized method that gets called upon success for all jQuery ajax requests. Other global ajax handlers are listed here.


One possible way would be to set up a converter:

For instance, I use one to detect my asp.net version (3.5+ returns stuff differently) for existance of the "d" property:

$.ajaxSetup(
    {
    data: "{}",
    dataType: "jsond",
    type: "POST",
    contentType: "application/json",
    converters:
    {
        "json jsond": function(msg) {
        return msg.hasOwnProperty('d') ? msg.d : msg;
        }
    }
});

You could likewise do the same with success:

$.ajaxSetup(
    {
    data: "{}",
    dataType: "json",
    type: "POST",
    contentType: "application/json",
    success:
    {
        "json": function(msg) {
            MyGlobalvariable = msg.hasOwnProperty('MyFlag') ? msg.MyFlag : "";
        }
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消