2010-05-28 81 views
4

如果我的Ajax調用返回成功的結果,但是在處理結果時導致異常,則會觸發錯誤處理程序。這對我來說似乎是非常直觀的,因爲我認爲錯誤處理程序應該只在由於進行Ajax調用或通過服務器端錯誤而發生錯誤時觸發。我試圖在單元測試中使用Ajax函數,所以我想告訴兩種不同的故障情況。有沒有辦法繞過jQuery錯誤處理程序?

+0

嗯,我從來不知道。這可能是由於jQuery對AJAX進程的內部處理而不是設計,但它仍然是應該修復的。 – Matchu 2010-05-28 02:01:55

回答

1

原諒我,如果我解釋這完全錯了,但似乎你對有關.ajaxError() handler,您可以使用像這樣專門找:

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

或者你可以將其綁定,這是ajaxError事件,就像click事件一樣。這隻適用於AJAX錯誤,而不是任何jQuery拋出,那是你在做什麼?

0

我剛剛在下面進行了測試。如果傳回HTTP 200,它不會拋出錯誤。 var'result'包含你期望的任何東西。如果您不想使用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 
    }; 
}