如何创建全局ajax成功处理程序?

时间:2013-05-31 13:18:15

标签: javascript jquery ajax

我有ajax请求:

$.post(url, function (result) { //some code })

结束我需要全局ajaxSuccess

$(document).ajaxSuccess(function (event, xhr, settings) {
            var redirectTo = xhr.getResponseHeader('RedirectTo');
            if (redirectTo) {
                window.location = redirectTo;
                xhr.abort();
            }
        });

现在第一个电话是post。第二个ajaxSuccess

我需要首先调用ajaxSuccess

实际:     / *     控制台结果

ajaxSend
post
ajaxSuccess
*/

预期:     / *     控制台结果

ajaxSend
ajaxSuccess
post
*/

1 个答案:

答案 0 :(得分:1)

我认为你想要一些与ajaxSuccess()方法相反的方法。它是ajaxSend() method

$(document).ajaxSend(function (event, xhr, settings) {
  console.log("ajaxSend");
});

$(document).ajaxSuccess(function (event, xhr, settings) {
  console.log("ajaxSuccess");
});

$.post(url, function (result) {
  console.log("post");
});


/*
console result

ajaxSend
post
ajaxSuccess
*/

已添加:您可以这样做,但我不建议使用以下代码。选择这个想法。

(function ($) {
        $.post = function (url, data, callback, type) {
            // shift arguments if data argument was omitted
            if (jQuery.isFunction(data)) {
                type = type || callback;
                callback = data;
                data = undefined;
            }

            return jQuery.ajax({
                    url: url,
                    type: "POST",
                    dataType: type,
                    data: data,
                    success: function (success, statusText, jqXHR) {
                        jQuery.event.trigger("ajaxCallbackBefore", [jqXHR, success]);
                        callback(success, statusText, jqXHR);
                    }
                });
        };
    })(jQuery);

jQuery.fn.ajaxCallbackBefore = function (fn) {
    return this.on("ajaxCallbackBefore", fn);
};

$(function () {
        $(document).ajaxCallbackBefore(function () {
                console.log("ajaxCallbackBefore");
            });
        $(document).ajaxSend(function () {
                console.log("ajaxSend");
            });
        $(document).ajaxSuccess(function () {
                console.log("ajaxSuccess");
            });

        $.post(url, function (result) {
                console.log("post");
            });
    });