有什么方法可以在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。

我不知道我错在哪里。我可以做什么来解决这个问题?


当前回答

这可能是由于JSON字段名没有引号导致的。

更改JSON结构:

{welcome:"Welcome"}

to:

{"welcome":"Welcome"}

其他回答

我相信Ajax响应处理程序使用HTTP状态代码来检查是否存在错误。

因此,如果您只是在服务器端代码上抛出一个Java异常,但HTTP响应没有500状态代码,jQuery(或者在本例中可能是XMLHttpRequest对象)将假设一切正常。

我这么说是因为我在ASP.NET中遇到了类似的问题,我抛出了ArgumentException(“不知道该怎么做…”)之类的东西,但错误处理程序没有启动。

然后,无论是否有错误,我都将Response.StatusCode设置为500或200。

确保将Response.StatusCode设置为200以外的值。使用Response编写异常消息。Write,然后使用。。。

xhr.responseText

..在javascript中。

服务器端:

     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);
                 });

如果有人像2016年一样在这里寻找答案,请使用.fail()进行错误处理,因为.error()在jQuery 3.0中已被弃用

$.ajax( "example.php" )
  .done(function() {
    alert( "success" );
  })
  .fail(function(jqXHR, textStatus, errorThrown) {
    //handle error here
  })

我希望这有帮助

错误:函数(xhr,ajaxOptions,thrownError){警报(xhr.status);警报(thrownError);}代码内错误ajax请求捕获客户端到服务器之间的错误连接如果要显示应用程序的错误消息,请在成功范围内发送

例如

成功:函数(数据){//数据是对象发送表单服务器//数据的属性//状态类型布尔值//消息类型字符串//结果类型字符串if(data.status){//true not error$(“#api_text”).val(data.result);}其他的{$(“#error_text”).val(data.msg);}}