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

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


当前回答

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

例如

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

其他回答

这就是我所做的,它目前在MVC 5应用程序中运行。

控制器的返回类型为ContentResult。

public ContentResult DoSomething()
{
    if(somethingIsTrue)
    {
        Response.StatusCode = 500 //Anything other than 2XX HTTP status codes should work
        Response.Write("My Message");
        return new ContentResult();
    }

    //Do something in here//
    string json = "whatever json goes here";

    return new ContentResult{Content = json, ContentType = "application/json"};
}

在客户端,这是ajax函数的样子

$.ajax({
    type: "POST",
    url: URL,
    data: DATA,
    dataType: "json",
    success: function (json) {
        //Do something with the returned json object.
    },
    error: function (xhr, status, errorThrown) {
        //Here the status code can be retrieved like;
        xhr.status;

        //The message added to Response object in Controller can be retrieved as following.
        xhr.responseText;
    }
});

服务器端:

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

尽管这个问题已经问了很多年了,但我仍然没有找到xhr.responseText作为我一直在寻找的答案。它以以下格式返回字符串:

"{"error":true,"message":"The user name or password is incorrect"}"

我绝对不想向用户展示。我要找的东西如下:

alert(xhr.responseJSON.message);

xhr.responseJSON.message为我提供了Json对象的确切消息,该消息可以显示给用户。

通用/可重复使用的解决方案

这个答案是为将来遇到这个问题的所有人提供的参考。解决方案由两部分组成:

在服务器上验证失败时引发的自定义异常ModelStateException(当我们使用数据注释并使用强类型控制器操作参数时,模型状态报告验证错误)自定义控制器操作错误筛选器HandleModelStateExceptionAttribute,它捕获自定义异常并返回HTTP错误状态,主体中包含模型状态错误

这为jQueryAjax调用提供了最佳的基础设施,以便在成功和错误处理程序中充分发挥其潜力。

客户端代码

$.ajax({
    type: "POST",
    url: "some/url",
    success: function(data, status, xhr) {
        // handle success
    },
    error: function(xhr, status, error) {
        // handle error
    }
});

服务器端代码

[HandleModelStateException]
public ActionResult Create(User user)
{
    if (!this.ModelState.IsValid)
    {
        throw new ModelStateException(this.ModelState);
    }

    // create new user because validation was successful
}

整个问题在这篇博客文章中有详细介绍,您可以在其中找到在应用程序中运行此功能的所有代码。

该函数基本上生成唯一的随机API密钥,如果没有,则会出现带有错误消息的弹出对话框

在视图页面中:

<div class="form-group required">
    <label class="col-sm-2 control-label" for="input-storename"><?php echo $entry_storename; ?></label>
    <div class="col-sm-6">
        <input type="text" class="apivalue"  id="api_text" readonly name="API" value="<?php echo strtoupper(substr(md5(rand().microtime()), 0, 12)); ?>" class="form-control" />                                                                    
        <button type="button" class="changeKey1" value="Refresh">Re-Generate</button>
    </div>
</div>

<script>
$(document).ready(function(){
    $('.changeKey1').click(function(){
          debugger;
        $.ajax({
                url  :"index.php?route=account/apiaccess/regenerate",
                type :'POST',
                dataType: "json",
                async:false,
                contentType: "application/json; charset=utf-8",
                success: function(data){
                  var result =  data.sync_id.toUpperCase();
                        if(result){
                          $('#api_text').val(result);
                        }
                  debugger;
                  },
                error: function(xhr, ajaxOptions, thrownError) {
                  alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
                }

        });
    });
  });
</script>

来自控制器:

public function regenerate(){
    $json = array();
    $api_key = substr(md5(rand(0,100).microtime()), 0, 12);
    $json['sync_id'] = $api_key; 
    $json['message'] = 'Successfully API Generated';
    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
}

可选的回调参数指定在load()方法完成时要运行的回调函数。回调函数可以有不同的参数:

类型:函数(jqXHRjqXHR,字符串文本状态,字符串错误抛出)

请求失败时要调用的函数。该函数接收三个参数:jqXHR(在jQuery1.4.x中,XMLHttpRequest)对象、描述发生的错误类型的字符串和可选的异常对象(如果发生)。第二个参数的可能值(除了null)是“超时”、“错误”、“中止”和“parserror”。当发生HTTP错误时,errorThrown会接收HTTP状态的文本部分,例如“未找到”或“内部服务器错误”。从jQuery 1.5开始,错误设置可以接受一系列函数。将依次调用每个函数。注意:跨域脚本和跨域JSONP请求不会调用此处理程序。