【问题标题】:Intercept jQuery.ajax's 'success' callback function before execution执行前拦截jQuery.ajax的'success'回调函数
【发布时间】:2012-03-09 13:05:25
【问题描述】:

我已经构建了一个 Web 应用程序,它在几十个不同的页面上大量使用了 jQuery.ajax() 函数。自然地,每次使用 jQuery.ajax() 都会传递一个配置对象,该对象带有一个函数,作为 'success' 属性的回调。

我现在遇到一种情况,如果服务器为任何给定的 ajax 请求返回某个错误代码,我想在多个页面上全局执行某个操作。我正在考虑通过在我的页面标题中包含javascript来以某种方式覆盖jQuery库的一部分,这将执行条件检查操作,然后继续执行在配置对象中传递的任何回调函数。这可能吗?我目前正在审查 jQuery 库的源代码,看看我是否可以这样做。

【问题讨论】:

    标签: javascript jquery ajax callback


    【解决方案1】:

    我认为您需要查看全局 Ajax 事件处理程序。

    http://api.jquery.com/category/ajax/global-ajax-event-handlers/

    【讨论】:

    • 全局 ajax 事件处理程序在成功回调(例如)被触发后被触发。如果 OP 想要在触发实际成功之前做某事,他将无法使用全局事件处理程序来完成。
    【解决方案2】:

    在 jQuery 1.5+ 中,您可以通过$.ajaxconverters 选项来完成此操作。通常,转换器只是应该转换从 Web 服务器接收到的数据,并将其传递给成功回调,但如果需要,您可以在其中运行其他代码。

    将此代码放入嵌入所有页面的 js 文件中。

    $.ajaxSetup({
        // the converter option is a list of dataType-to-dataType conversion functions 
        // example: converters['text json'] is a function that accepts text and returns an object
        // note: to redefine any single converter, you must redefine all of them
        converters: {
            "text json": function (text) {
                // NOTE: this converter must return a parsed version of the json                
                var result = jQuery.parseJSON(text);
                if (result.errorMessage) {
                    // catch the error message and alert
                    alert(result.errorMessage)
                }
                return result;            
            },
            "text html": true,          
            "* text": window.String,
            "text xml": jQuery.parseXML
        }
    });
    

    完整示例: http://jsfiddle.net/waltbosz/8a8fZ/

    【讨论】:

      【解决方案3】:

      我最终使用$.ajaxSetup 以全局方式覆盖了成功回调,如下所示:

      $.ajaxSetup({
          beforeSend: function(xhr, options) {
              var originalSuccess = options.success
              options.success = function(data, textStatus, jqXhr) {
                  // trigger some sort of event here for interested listeners
                  originalSuccess.apply(this, arguments)
              }
          }
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-30
        • 2018-08-25
        • 1970-01-01
        • 2013-11-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多