有什么方法可以在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对象中有一个抛出异常的JSON对象。只需使用

alert(xhr.responseJSON.Message);

JSON对象公开了其他两个财产:“ExceptionType”和“StackTrace”

其他回答

在我的例子中,我刚刚从控制器中删除了HTTPVERB。

    **//[HttpPost]**   ---- just removed this verb
    public JsonResult CascadeDpGetProduct(long categoryId)
    {
       
        List<ProductModel> list = new List<ProductModel>();
        list = dp.DpProductBasedOnCategoryandQty(categoryId);
        return Json(new SelectList(list, "Value", "Text", JsonRequestBehavior.AllowGet));
    }
$("#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({...

......});

这就是我所做的,它目前在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;
    }
});

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

例如

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

您需要将responseText转换为JSON。使用JQuery:

jsonValue = jQuery.parseJSON( jqXHR.responseText );
console.log(jsonValue.Message);