Rails unobtrusive javascript (UJS) ajax:before app

2019-05-27 11:57发布

I'm trying to append some parameters to a form before sending via ajax (via Rails UJS).

  $(document).on("ajax:before",".form-example", function(event) {
    event.data = $(":hidden").serialize();
  });

The hidden inputs aren't within the form, so I need to collect them, serialize the, and add them to the request (which is a PUT request). However, in the above example, no parameters are being passed to the server, am I doing something wrong? How can I pass parameter called "items" with the serialized values of hidden inputs?

1条回答
你好瞎i
2楼-- · 2019-05-27 12:39

Looking into this, it is actually possible to do, but you do not use the event, you modify the form itself (using $(this)).

So something like this could work:

$(document).on("ajax:before",".form-example", function() {
  var form = $(this);
  form.append($('<input />',{name: 'hidden_values',value: $(":hidden").serialize()}));
});

And you should be able to access the data in your rails action using params[:hidden_values].

查看更多
登录 后发表回答