有什么方法可以在jQueryAJAX错误消息中显示自定义异常消息作为警报吗?
例如,如果我想通过抛出新的ApplicationException(“用户名已经存在”),通过Struts在服务器端抛出异常;,我想在jQueryAJAX错误消息中捕获此消息(“用户名已存在”)。
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);
}
});
}
});
在错误回调中的第二个警报中,我向thrownError发出警报,我得到了未定义,xhr.status代码为500。
我不知道我错在哪里。我可以做什么来解决这个问题?
首先,我们需要在web.config中设置<serviceDebug includeExceptionDetailInFaults=“True”/>:
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
**<serviceDebug includeExceptionDetailInFaults="true" />**
</behavior>
</serviceBehaviors>
除了jquery级别的错误部分,您还需要解析包含异常的错误响应,如:
.error(function (response, q, t) {
var r = jQuery.parseJSON(response.responseText);
});
然后使用r.Message,您可以实际显示异常文本。
检查完整代码:http://www.codegateway.com/2012/04/jquery-ajax-handle-exception-thrown-by.html
使用以下命令在服务器上引发新异常:
Response.StatusCode=500
Response.StatusDescription=例如消息()
我认为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
$("#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({...
......});
服务器端:
doPost(HttpServletRequest request, HttpServletResponse response){
try{ //logic
}catch(ApplicationException exception){
response.setStatus(400);
response.getWriter().write(exception.getMessage());
//just added semicolon to end of line
}
}
客户端:
jQuery.ajax({// just showing error property
error: function(jqXHR,error, errorThrown) {
if(jqXHR.status&&jqXHR.status==400){
alert(jqXHR.responseText);
}else{
alert("Something went wrong");
}
}
});
一般Ajax错误处理
如果我需要对所有ajax请求进行一些通用错误处理。我将设置ajaxError处理程序,并在html内容顶部名为errorcontainer的div上显示错误。
$("div#errorcontainer")
.ajaxError(
function(e, x, settings, exception) {
var message;
var statusErrorMap = {
'400' : "Server understood the request, but request content was invalid.",
'401' : "Unauthorized access.",
'403' : "Forbidden resource can't be accessed.",
'500' : "Internal server error.",
'503' : "Service unavailable."
};
if (x.status) {
message =statusErrorMap[x.status];
if(!message){
message="Unknown Error \n.";
}
}else if(exception=='parsererror'){
message="Error.\nParsing JSON Request failed.";
}else if(exception=='timeout'){
message="Request Time out.";
}else if(exception=='abort'){
message="Request was aborted by the server";
}else {
message="Unknown Error \n.";
}
$(this).css("display","inline");
$(this).html(message);
});