有沒有什麼方法能夠在個人jQuery AJAX錯誤消息中顯示自定義異常消息做爲警報? html
例如,若是我想經過扔在服務器端異常的Struts經過throw new ApplicationException("User name already exists");
,我想在jQuery AJAX錯誤消息中捕獲此消息('用戶名已存在')。 jquery
jQuery("#save").click(function () { if (jQuery('#form').jVal()) { jQuery.ajax({ type: "POST", url: "saveuser.do", dataType: "html", data: "userId=" + encodeURIComponent(trim(document.forms[0].userId.value)), success: function (response) { jQuery("#usergrid").trigger("reloadGrid"); clear(); alert("Details saved successfully!!!"); }, error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); } }); } });
在第二個警報,我警告拋出的錯誤,我獲得undefined
,狀態代碼是500。 web
我不肯定我哪裏出錯了。 我該怎麼作才能解決這個問題? ajax
首先,咱們須要在web.config中設置<serviceDebug includeExceptionDetailInFaults =「True」/>: 服務器
<serviceBehaviors> <behavior name=""> <serviceMetadata httpGetEnabled="true" /> **<serviceDebug includeExceptionDetailInFaults="true" />** </behavior> </serviceBehaviors>
除了在錯誤部分的jquery級別,你須要解析包含異常的錯誤響應,如: asp.net
.error(function (response, q, t) { var r = jQuery.parseJSON(response.responseText); });
而後使用r.Message,您能夠實際顯示異常文本。 ssh
查看完整代碼: http : //www.codegateway.com/2012/04/jquery-ajax-handle-exception-thrown-by.html post
若是調用asp.net,這將返回錯誤消息標題: this
我本身並無編寫全部的formatErrorMessage,但我發現它很是有用。 url
function formatErrorMessage(jqXHR, exception) { if (jqXHR.status === 0) { return ('Not connected.\nPlease verify your network connection.'); } else if (jqXHR.status == 404) { return ('The requested page not found. [404]'); } else if (jqXHR.status == 500) { return ('Internal Server Error [500].'); } else if (exception === 'parsererror') { return ('Requested JSON parse failed.'); } else if (exception === 'timeout') { return ('Time out error.'); } else if (exception === 'abort') { return ('Ajax request aborted.'); } else { return ('Uncaught Error.\n' + jqXHR.responseText); } } var jqxhr = $.post(addresshere, function() { alert("success"); }) .done(function() { alert("second success"); }) .fail(function(xhr, err) { var responseTitle= $(xhr.responseText).filter('title').get(0); alert($(responseTitle).text() + "\n" + formatErrorMessage(xhr, err) ); })
使用如下命令在服務器上拋出新的異常:
Response.StatusCode = 500
Response.StatusDescription = ex.Message()
我相信StatusDescription會返回到Ajax調用...
例:
Try Dim file As String = Request.QueryString("file") If String.IsNullOrEmpty(file) Then Throw New Exception("File does not exist") Dim sTmpFolder As String = "Temp\" & Session.SessionID.ToString() sTmpFolder = IO.Path.Combine(Request.PhysicalApplicationPath(), sTmpFolder) file = IO.Path.Combine(sTmpFolder, file) If IO.File.Exists(file) Then IO.File.Delete(file) End If Catch ex As Exception Response.StatusCode = 500 Response.StatusDescription = ex.Message() End Try
$("#save").click(function(){ $("#save").ajaxError(function(event,xhr,settings,error){ $(this).html{'error: ' (xhr ?xhr.status : '')+ ' ' + (error ? error:'unknown') + 'page: '+settings.url); }); });
$("#fmlogin").submit(function(){ $("#fmlogin").ajaxError(function(event,xhr,settings,error){ $("#loading").fadeOut('fast'); $("#showdata").fadeIn('slow'); $("#showdata").html('Error please, try again later or reload the Page. Reason: ' + xhr.status); setTimeout(function() {$("#showdata").fadeOut({"opacity":"0"})} , 5500 + 1000); // delays 1 sec after the previous one }); });
若是有任何表格提交驗證
只需使用其他的代碼
$("#fmlogin").validate({...
... ... });