【问题标题】:How to render ajax error from a controller如何从控制器呈现 ajax 错误
【发布时间】:2014-02-04 10:38:23
【问题描述】:

我正在使用 ajax 提交表单。

在我的控制器中,我有类似的东西:

if @message.valid?
 render json: { msg: @message.content }
else
 render json: { error: 'Reply could not be sent.' }
end

在我看来,我有表格

<%= form_for @message, remote: true do |f| %>

然后在我看来,我有以下 javascript

$('.message').bind('ajax:success', function(xhr, data, status) {
 $(this).before('<p>'+data.msg+'</p>');
  });

$('.message').bind('ajax:error', function() {
 alert("Error: Message could not be sent.");
});

我无法启动 ajax 错误。我假设它是如何在控制器中传递 json 错误消息的。

【问题讨论】:

  • 你使用了远程 ajax 吗?
  • 是的。我会补充问题
  • add (xhr, status, error) inside second function() 可能有帮助,不确定...

标签: javascript ruby-on-rails ruby ajax json


【解决方案1】:

您需要告诉您的控制器这是作为 en 错误返回的。我通常使用响应状态 422(无法处理的实体),但是在您的情况下使用另一个错误代码可能更合适。

 if @message.valid?
   render json: { msg: @message.content }
 else
   render json: { error: 'Reply could not be sent.' }, status: 422
 end

您可以阅读有关响应状态的信息here(请特别注意错误 418 :))

【讨论】:

    【解决方案2】:

    当您将响应发送回没有任何状态的 ajax 时,它假定状态为 200(成功)。除非您遇到语法错误或某些授权错误,否则 ajax 将始终进入成功状态。由于它是您的自定义错误,我建议不要使用 http 状态代码。 相反,您可以修改 'ajax:success' 回调函数。

    `

    $('.message').bind('ajax:success', function(xhr, data, status) {
       if(data.error){
         alert(data.error);
       }
       else{
         $(this).before('<p>'+data.msg+'</p>');
       }
    })
    

    `

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-07
      • 1970-01-01
      相关资源
      最近更新 更多