如何获取ajax调用的默认错误

好吧,我想要做的是根据其错误代码警告ajax错误,我在网站上有很多ajax调用,所以我使用全局ajaxerror handling函数。

但我想要的是,如果一些ajax调用已经有默认错误,那么显示那里没有全局。

$(document).ready(function(){ $(document).ajaxError(e,xhr,opt){ if(xhr.error){ //Don't do anything } else { alert('You have an error'); } } } 

第一function:

 $.ajax({ type:"post", url:"page.php", data:"name=mohit&lastname=bumb", error:function(){ alert('error'); } }); 

第二function:

 $.ajax({ type:"post", url:"page.php", data:"name=mohit&lastname=bumb", }); 

所以在第二种情况下它应该显示你有一个错误 ,在第一种情况下只是错误

是的,你可以,但你必须覆盖jQuery默认的$.ajax方法。 检查我在其中一个项目中使用的以下代码。 确保在jQuery之后加载脚本。

我的情景是 –

  1. 该网站有很多ajax部分视图,必须检查用户是否登录。 所以我不得不重写jquery调用来检查它。

  2. 当进行任何ajax调用时,我还必须显示一个加载器。

  3. 还有一件事,一些js是由ajax加载的,所以我添加了一个检查url是.js文件还是普通url。

我已经取出了对我的项目保密的敏感代码。 剩下的就在这里。 这可能对你有帮助。

 $(document).ready(function () { var oldjQuery = []; oldjQuery["ajax"] = $.ajax; oldjQuery["load"] = $.load; var newOptions = []; //override ajax jQuery.ajax = function (options) { newOptions["ajax"] = $.extend({}, options); //override the success callback newOptions["ajax"].success = function (data, textStatus, jqXhr) { try { if (options.url.indexOf('.js') <= -1) { //this is a normal success call, do nothing } } catch (err) { //... my other codes, incase any error occurred } if (typeof options.success != 'undefined') { //the ajax call has a success method specified, so call it options.success(data, textStatus, jqXhr); } }; //override the error callback newOptions["ajax"].error = function (jqXhr, textStatus, errorThrown) { try { if (options.url.indexOf('.js') <= -1) { //this is a normal success call, do nothing } }catch (y) { //... my other codes, incase any error occurred } //the ajax call has an error method specified, so call it if (typeof options.error != 'undefined') { options.error(jqXhr, textStatus, errorThrown); } }; return oldjQuery["ajax"](newOptions["ajax"]); }; //override load function jQuery.load = function (url, data, completeCallback, ignore) { newOptions["load"].completeCallback = function (d, textStatus, jqXhr) { try { if (url.indexOf('.js') <= -1) { //codes } } catch (err) { try { //codes }catch (err2) { } } if (typeof completeCallback != 'undefined') { //call the default completed callback completeCallback(d, textStatus, jqXhr); } }; return oldjQuery["load"](url, data, newOptions["load"].completeCallback); }; });