【问题标题】:How to retrieve error message from an AJAX error callback in Grails?如何从 Grails 中的 AJAX 错误回调中检索错误消息?
【发布时间】:2010-08-05 22:03:23
【问题描述】:

我正在发送以下 AJAX 请求:

$.ajax({ type: 'POST',
  data: $(this).parents('form:first').serialize(), url:'/myapp/comment/saveOrUpdate',
  success: function(data,textStatus) {insertNewComment(data)},
  error: function(xhr, textStatus, errorThrown) {alert(xhr.responseText);}
})

...我的控制器操作如下所示:

class CommentController {
...
def saveOrUpdate = {
   ...
   if (error) {
      response.sendError 419, 'You must wait at least 5 minutes before posting a new comment'
   }
}}

不幸的是,我从未在 HTTP 响应中看到我发送的消息。相反,我得到了一个从 Tomcat/Apache(或 Grails?)生成的错误 HTML 页面,如下所示:

<html><head><title>Apache Tomcat/6.0-snapshot - Error report</title>
</head><body><h1>HTTP Status 419 - </h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>Cannot find message associated with key http.419</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/6.0-snapshot</h3></body></html>

如何绕过生成的错误 HTML 页面,以便从 JavaScript 代码中检索消息“您必须等待...”?

感谢您的帮助。

【问题讨论】:

    标签: jquery ajax grails error-handling http-status-codes


    【解决方案1】:

    您正在设置一个 HTTP 状态错误,但实际上您遇到了一个业务逻辑问题——一个应用程序错误。为什么不直接设置适当的应用程序级状态代码和消息(您自己设计的),并在 ajax 响应中返回它们(包括剩余时间)?如果依赖 HTTP 错误代码,在不同的浏览器中可能会得到不同的结果,其中一些会在错误页面小于 512 字节时劫持错误消息。

    在您引用的情况下,Apache 找不到与 419 匹配的已知错误消息。

    您可以在 .htaccess 配置中添加一个:

    ErrorDocument 419 /errordocs/419.html
    

    ...然后让 419.html 页面说出你喜欢的任何内容(并确保页面超过 512 字节)。但我敢打赌,使用应用程序级状态代码是您正在寻找的。​​p>

    【讨论】:

    • 我已经按照您的建议实现了应用程序级状态代码。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多