有没有办法绕过jQuery错误处理程序?

时间:2010-05-28 01:55:35

标签: jquery

如果我的Ajax调用返回一个成功的结果,但在处理结果时导致异常,则会触发错误处理程序。这似乎与我相反,因为我认为错误处理程序只应在由于进行Ajax调用或服务器端错误而发生错误时触发。我试图在单元测试中使用Ajax函数,所以我想告诉两种不同故障情况之间的区别。

2 个答案:

答案 0 :(得分:1)

请原谅我,如果我解释这个完全错误,但似乎你正在寻找.ajaxError() handler,你可以这样使用:

$(document).ajaxError(function(event, xmlHttp, options, error) {
  alert(error); 
});

或者您可以绑定它,它是ajaxError事件,就像click事件一样。这只是针对AJAX错误而不是任何jQuery抛出,那是你所追求的吗?

答案 1 :(得分:0)

我刚刚用下面的测试进行了测试。如果传回HTTP 200,它不会抛出错误。 var' results'包含您期望的任何内容。如果您不想使用JSON,请删除数据类型。

function ajaxRequest(request, url) {
  $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: url,
    data: data,
    dataType: "json",
    cache: false,
    async: false,
    success: function(result) {
      //this only happens on success
    },
    error: function(msg,XMLStatus,Err) {      
      ajaxError(msg,XMLStatus,Err); //Call generic error message
    }
  });
}

我倾向于将此作为Web服务交互的通用成功/错误方法。


/* Data must be prepared in a standard JSON format, either using $.toJSON() for objects, or stringbuilding for individual parameters */

/* General AJAX request handler */
/* serviceName is the full path of the service ie. "fullpath/services/service.asmx/method/" */

function ajaxRequest(data, serviceName, callbackFunction, async) {  
  $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: serviceName,
    data: data,
    dataType: "json",
    cache: false,
    async: async,
    success: function(response) {
      callbackFunction.Success(response);
    },
    error: function(msg,XMLStatus,Err) {      
      callbackFunction.Error(msg,XMLStatus,Err);
    }
  });
}

/* Sample use */
function getStuff(a,b,c){
  //Sample method signiture: getStuff(string a, string b, string c)
  var data = "{"
    data += "'a'" + ":'" + a + "'"
    data += ",'b'" + ":'" + b + "'"
    data += ",'c'" + ":'" + c + "'"
  data += "}";
  someParameterImayWantToUseInTheCallBack = "This was the test click button";
  serviceName = "/taccapps/samples/servicesample.asmx/getStuff/";
  ajaxRequest(data, serviceName, new sampleCallback(someParameterImayWantToUseInTheCallBack), true);
}

/* Sample callback */
function sampleCallback(someParameterImayWantToUseInTheCallBack){
  //someParameterImayWantToUseInTheCallBack is available to both the success and fail methods
  this.Success(response){
    //"response" represents the JSON response from the server. If it is a list/array it can be dotted into using the index.
    for(item in response){
      alert(response[item].a);
      alert(response[item].b);
      alert(response[item].c);
    }    
  };
  this.Error(msg,XMLStatus,err){
    //Standard HTTP error codes are found in the above
  };
}