Rails 5,remote: true表单无数据

9

我正在尝试将Rails 4.2应用程序迁移到Rails 5.1。在Rails 4.2中,我们大量使用JQuery。目前我正在努力使带有remote: true属性的表单正常工作。这是一个简单的表单示例,用户选择国家:

= simple_form_for(:user_data,
  url: user_path(@user),
  remote: true,
  method: :patch,
  data: {'user-update' => true},
  dataType: 'json',
  html: wrapper: :horizontal_form ) do |f|
  .panel.panel-default
    .panel-body
      .col-md-8
        = f.input :country, label: 'Country',
      = f.button :submit  

控制器
def update
  @user.update!(user_params)
  render json: @user
end

我尝试使用respond_tojs响应格式,但在这种情况下,它会尝试将@user转换为可执行的javascript代码。因此,事件处理程序看起来像这样:

  $('form[data-user-update]')
  .on('ajax:success', function(e, data, status, xhr) {
     // The data variable is empty
  })
  .on('ajax:error', function(e, error, status, xhr) {
    $('.simple_form').renderFormErrors('user_data', error.responseJSON);
  });

编辑

响应头

HTTP/1.1 200 OK
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Content-Type: application/json; charset=utf-8
ETag: W/"f53889092c58dc37054386c9504ad1ff"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: 712b59ff-8011-4b10-a905-83e559b47452
X-Runtime: 0.101165
Transfer-Encoding: chunked

请求头

Accept:text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8,et;q=0.6
Connection:keep-alive
Content-Length:71
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:localhost:3000
Origin:http://localhost:3000
Referer:http://localhost:3000/users/470d573b-b0f1-4822-b036-7d37be6672d6
X-Requested-With:XMLHttpRequest

响应

{ 
  firstName:'John',
  lastName: 'Smith',
  country: 'USA'
}

你能通过开发者工具检查服务器的响应吗?(在Chrome中,选择“网络”选项卡,进行远程提交表单,找到请求并分析HTTP请求/响应) - MrYoshiji
@MrYoshiji,请查看更新。 - mr. Holiday
如果在ajax:success回调中放置了一个debugger,您能否看到edata等的任何值? - MrYoshiji
e.data 包含什么内容? - MrYoshiji
我在我的应用程序中看到了完全相同的行为。只有一个事件被传递,其他所有内容都是未定义的。 - TomD
显示剩余3条评论
1个回答

11

在遇到同样的问题时,我刚刚解决了它。

根据http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html#dealing-with-ajax-events,我假设您正在使用rails-ujs而不是较旧的jquery-ujs。在jquery-ujs中,代码可以工作并返回data、status和xhr;但是,在rails-ujs中,仅返回一个属性-event,并且可以通过event.details数组访问其他内容。

如指南中的例子所示:

document.body.addEventListener('ajax:success', function(event) {
  var detail = event.detail;
  var data = detail[0], status = detail[1],  xhr = detail[2];
})

您可以通过调用 event.detail[0] 来访问响应。

如果您的代码相当依赖此功能,最好的选择可能是将 rails-ujs 更改回 jquery-ujs。


1
令人沮丧的是,官方文档也已经过时了。 - dimroc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接