8

我可能偏离了方向,但我想知道是否可以使用 JQuery预过滤器功能并分析 Ajax Success 中的响应数据,并根据我返回的 JSON 中某些元素的存在有条件地转发到error我的调用中的事件处理程序ajax(错误消息)。

如果这是为页面中的任何 ajax 函数全局设置的,那就太好了。

也许这不是解决这个问题的最佳方法;如果有人有其他想法,请告诉我!

前置过滤器:

//only run prefilter on ajax calls expecting JSON back in response, would this 
//be the right way to do this? 
$.ajaxPrefilter( "json", function( options, originalOptions, jqXHR ) {
    jqXHR.success(function(data, textStatus, jXHR) {
        if( hasErrors(data) ) {
           //forward to error event handler?
        }
    });
});

阿贾克斯调用:

$.ajax({
      type:     "POST",
      data:     {  
                    theData: "someData"                    
                },
      url:      theUrl,
      dataType: 'json',
      cache:    false,          
      success:  function (data, textStatus, jqXHR) {
                    //do stuff on success
                }
      error:    function ( jqXHR, textStatus, errorThrown ) {
                    //I want to do this stuff if data contains errors from server
                } 
 });

太感谢了!

4

1 回答 1

16

我是这样做的:我存储原始成功函数(特定于每个请求),然后附加另一个回调。如果它没有错误,我调用原始回调:

$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
    var originalSuccess = options.success;

    options.success = function (data) {
        if(hasErrors(data)) {
           //forward to error event handler or redirect to login page for example
        }
        else {
            if (originalSuccess != null) {
                originalSuccess(data);
            }
        }   
    };
});
于 2011-06-16T14:57:23.437 回答