有没有什么方法能够在个人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({...
... ... });