【问题标题】:How can I associate error messages to the 'error' key in json response如何将错误消息与 json 响应中的“错误”键相关联
【发布时间】:2012-10-28 13:51:51
【问题描述】:

我试图通过上传文件(文件名、大小)来显示可能发生的错误。 我正在使用an adapted version of Jquery Fiel Upload for Ruby on Rails

我需要将我的错误消息(验证)关联到我的 json 响应中的“错误”键。

我想我必须更改 javascript 才能使其工作。

json:

render json: {error: @upload.errors.full_messages}, status: :unprocessable_entity

验证:

 validates_uniqueness_of :upload_file_name, :message => "File with this name is already in the database"
     
 validates :upload_file_size,  :inclusion  => {:in =>10.megabytes..20.megabytes}, :message =>"Too big or too small"

我用来上传文件的Javascript:

<script type="text/javascript" charset="utf-8">
      $(function () {
          // Initialize the jQuery File Upload widget:
          $('#fileupload').fileupload();
          // 
          // Load existing files:
          $.getJSON($('#fileupload').prop('action'), function (files) {
            var fu = $('#fileupload').data('fileupload'), 
              template;
            fu._adjustMaxNumberOfFiles(-files.length);
            console.log(files);
            template = fu._renderDownload(files)
              .appendTo($('#fileupload .files'));
            // Force reflow:
            fu._reflow = fu._transition && template.length &&
              template[0].offsetWidth;
            template.addClass('in');
            $('#loading').remove();
          });
    
      });
    </script>

我也尝试过这些事情: json: =&gt; [{:error=&gt; @upload.errors.full_messages }] } 使用它只显示验证消息,但我需要状态:以及

【问题讨论】:

    标签: javascript ruby-on-rails json


    【解决方案1】:

    解决办法如下:

    json:

    format.json{ render json: {error: @upload.errors.full_messages}, :status =>422}
    

    javascript(主要代码的截断)

    $('#fileupload').fileupload({       
    
    
            error: function(xhr){
              var errors = $.parseJSON(xhr.responseText).error
              alert(errors)         
            }
                  });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-15
      • 2011-03-28
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      • 2013-02-17
      • 1970-01-01
      • 2022-06-25
      相关资源
      最近更新 更多