全局过滤ajax成功处理程序

时间:2013-04-28 03:17:38

标签: jquery ajax event-handling

我正在开发单页ASP.NET MVC 3应用程序。所有帖子均由ajax来电完成。用户几乎可以看到页面上的所有内容,但有些操作需要用户登录。

如果某个操作需要登录,如果用户未登录,我会返回JSON {unauthenticated: true}。所以我有几个成功的处理程序,如:

success : function(response){
  if(response.unauthenticated){
    showLoginDialog();
  } else {
    doTheActualWork();
  }
}

我想在全局success处理程序中执行此操作。像:

$(document).ajaxSuccess(function (event, XMLHttpRequest, ajaxOptions){
  if(unauthenticated()){
    preventTheLocalSuccess();
    showLoginDialog();
  }
});

本地成功处理程序将是:

success: function(response){
  // No Checking
  doTheActualWork();
}

有办法吗?

2 个答案:

答案 0 :(得分:4)

你应该看一下dataFilter property of $.ajax。此属性接受一个函数,该函数在您收到请求之后但在执行任何处理程序之前执行。这样做的主要目的是预处理jQuery本身处理之前收到的数据。因此,您将收到原始数据。您可以在那里进行中间处理,例如登录。

要将此配置修补到所有ajax调用,我们使用$.ajaxSetup为所有ajax请求预定义dataFilter。因此,每个ajax请求都会在本地处理程序执行之前执行dataFilter处理程序。

至于示例代码,here's a demo, which pretty much works as expected

function login() {
    console.log('login initiated: you are not logged in');
}

$.ajaxSetup({
    dataFilter: function (origdata, type) {

        //the type is determined by the type you indicated in the ajax call
        //if not json, we return the data unharmed
        if (type !== 'json') return origdata;

        //data filter receives the raw response. since we have determined it's json
        //we parse it using jQuery's parseJSON to check the contents
        var data = $.parseJSON(origdata);

        if (data.auth) {
            //if logged in, we just return the data
            return origdata;
        } else {
            //otherwise, we execute the login
            //since returning something is required, we return false so local handler
            //data checks will fail against the false data
            login();
            return false;
        }
    }
});

//the url and data passed is for jsFiddle to work.

//logged in
$.post('/echo/json/', {
    json: JSON.stringify({
        auth: true
    })
}, function (data) {
    //in our handler, it's your normal "check data before use"
    //if data is truthy, it skips this check and moves on
    if(!data) return;
    console.log('data retrieved successfully', data);
}, 'json');

//not logged in
$.post('/echo/json/', {
    json: JSON.stringify({
        auth: false
    })
}, function (data) {
    //since we returned false, the code stops at this check
    if (!data) return;
    console.log('you should not see this since data is false, per dataFilter return', data);
}, 'json');

答案 1 :(得分:2)

而不是返回JSON返回正确的HTTP ERROR代码,在这种情况下,它将是401 Unauthorized。然后,您可以使用ajaxError方法来处理它。

$(document).ajaxError(function (event, XMLHttpRequest, ajaxOptions){
    switch (xhr.status) {
        case 401: // Unauthorized
             // Take action, referencing xhr.responseText as needed.
            showLoginDialog();
            return false;
            break; 
      }
});

此外,您可以扩展ajaxError条件以处理其他失败的请求。