Didn"t forge 2008-12-18 12:06 采纳率: 25%
浏览 1124

Ajax 错误处理,显示自定义异常消息

Is there some way I can show custom exception messages as an alert in my jQuery AJAX error message?

For example, if I want to throw an exception on the server side via Struts by throw new ApplicationException("User name already exists");, I want to catch this message ('user name already exists') in the jQuery AJAX error message.

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

On the second alert, where I alert the thrown error, I am getting undefined and the status code is 500.

I am not sure where I am going wrong. What can I do to fix this problem?

转载于:https://stackoverflow.com/questions/377644/jquery-ajax-error-handling-show-custom-exception-messages

  • 写回答

20条回答 默认 最新

  • 零零乙 2008-12-19 14:11
    关注

    I believe the Ajax response handler uses the HTTP status code to check if there was an error.

    So if you just throw a Java exception on your server side code but then the HTTP response doesn't have a 500 status code jQuery (or in this case probably the XMLHttpRequest object) will just assume that everything was fine.

    I'm saying this because I had a similar problem in ASP.NET where I was throwing something like a ArgumentException("Don't know what to do...") but the error handler wasn't firing.

    I then set the Response.StatusCode to either 500 or 200 whether I had an error or not.

    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程