在全球范围内过滤器的AJAX成功处理程序范围内、过滤器、程序、在全球

2023-09-10 19:53:06 作者:[降龙十巴掌]

我开发一个单页ASP.NET MVC 3应用程序。所有职位由 AJAX 的调用来完成。用户可以在网页上看到几乎所有的东西,但有些行动需要用户登录。

I am developing a single page ASP.NET MVC 3 application. All posts are done by ajax calls. The users can see almost everything on the page but some actions requires the user to login.

如果一个操作需要登录,我返回 JSON {未经验证:真} 如果用户没有登录在所以我有几个成功的处理程序,如:

If an action requires login, i return a JSON {unauthenticated: true} if the user is not logged in. So i have several success handlers like:

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

我想这样做在全球成功的处理程序。像:

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

和当地的成功处理程序为:

And the local success handler will be:

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

有没有办法做到这一点?

Is there a way to do that?

推荐答案

而不是返回JSON返回正确的HTTP错误code,在这种情况下将是一个 401未授权。然后,你可以使用 ajaxError 的方法来处理它。

instead of returning JSON return the proper HTTP ERROR Code, which in this case would be a 401 Unauthorized. Then you can use the ajaxError method to handle it.

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

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

Furthermore you can extend your ajaxError conditions to handle other failed requests.