【问题标题】:Rails 4 : ajax error not captured when using form_for w remote: true datatype :sonRails 4:使用 form_for w 远程时未捕获 ajax 错误:true 数据类型:son
【发布时间】:2016-02-15 04:50:45
【问题描述】:

我有一个表格(#new_group),写成:

   <%= form_for @group, remote: true, html: {role: :form, 'data-model' => 'group', class: 'form-horizontal', id: "new_group"} do |f| %>

我将所有 ajax 调用设置为 :json 数据类型

  //Default to JSON responses for remote calls
  $.ajaxSetup({
    dataType: 'json',
    cache: false
  })

提交表单,正确处理为:son

            def create
          @group =  Group.new(group_params)
          respond_to do |format|
            if @group.save
              format.html {  ... }
              format.json { ... }
            else 
              format.html { ... }
              format.json { 
                errors = {errors: @group.errors.full_messages}
                byebug
                render(json: errors.to_json, status: :unprocessable_entity )
              }
            end
          end

         debugging :
         (byebug) errors.inspect
         {:errors=>["Group already defined"]}

但是我可以在控制台中阅读:

POST http://localhost:3000/groups 422 (Unprocessable Entity)
XHR finished loading: POST "http://localhost:3000/groups"

为什么 422 http 错误没有被捕获为 ajax:error 事件? 我写道:

        $("#new_group")
            .on("ajax:success", function(e, data, status, xhr) {
              console.log("new group added!");
            })
            .on("ajax:error", function(e, data, status, xhr) {
              console.log("ERROR: " + status);
            errors = xhr.responseJSON.error;
        });

【问题讨论】:

    标签: ajax ruby-on-rails-4 http-error


    【解决方案1】:

    Rails 4 w turbolinks,我必须写:

          $(document).on('ajax:success', '#new_group', function(e, data, status, xhr) {
            console.log("data: "+JSON.stringify(data, null, 2));
          });
    
          $(document).on('ajax:error', '#new_group', function(e, data, status, xhr) {
            //console.log("data: "+JSON.stringify(data, null, 2));
            errors = data.responseJSON.errors; 
            $.each( errors, function( key, message ) {
              $("#modalGroupAlert ul").append( '<li>' + message + '</li>' );
            });
            $( "#modalGroupAlert" ).show();
          });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-25
      • 2021-11-09
      • 1970-01-01
      • 2019-12-08
      • 2017-06-16
      • 2012-12-11
      相关资源
      最近更新 更多