全局过滤ajax成功处理程序

我正在开发单页ASP.NET MVC 3应用程序。 所有post都是通过ajax调用完成的。 用户几乎可以看到页面上的所有内容,但有些操作需要用户登录。

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

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

我想在全局成功处理程序中执行此操作。 喜欢:

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

本地成功处理程序将是:

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

有没有办法做到这一点?

而不是返回JSON返回正确的HTTP错误代码,在这种情况下将是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条件以处理其他失败的请求。

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

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

至于示例代码, 这是一个演示,它几乎按预期工作 :

 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');