开发者

Global AJAX Success handler that inspects JSON data

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜