简体   繁体   English

在Rails中提交表单而无需重新加载页面

[英]submit form in Rails without page reload

I have a problem with preventing a pagereload on submitting a form. 我在阻止pagereload提交表单时遇到问题。

My HTML: 我的HTML:

<%= form_for @foo, html: {multipart: true}, remote: true do |f| %>
   <%= f.check_box :bar, :id => "bar_id", :onchange => "submit_function(this.form)" %>
<% end %>

My Javascript: 我的Javascript:

function submit_function(form){
    form.submit(function (ev) {
        ev.preventDefault();
    });
}

My Controller: 我的控制器:

def update

   // awesome things for update

   respond_to do |format|
     format.html { redirect_to request.referrer }
     format.js {}
   end
end

When clicking the checkbox , the JavaScript is triggered . 单击复选框时,将触发JavaScript。 The " form.submit " sends the form to the controller , but in this case the entire page is reloaded . “ form.submit”将表单发送到控制器,但是在这种情况下,整个页面被重新加载。 I would like to prevent this reload. 我想防止这种重新加载。

I've also tried this, however, the page is also reloaded. 我也尝试过此操作,但是页面也已重新加载。

function submit_function(form){
  form.submit(function () {
    $.ajax({
        type: this.method,
        url: this.action,
        data: $(this).serialize()
    });
    return false;
  });
}

Is it necessary the " submit - function" to change before or is it them by pressing the checkbox to change ? 是必须先更改“提交功能”还是通过单击复选框进行更改?

I have now tried something. 我现在尝试了一些东西。 Invites now the page no longer new, but the model is updated. 现在邀请页面不再是新的,但是模型已更新。

function submit_function(form) {

  $.ajax({
    type: form.method,
    url: form.action,
    data: $(form).serialize()
  });

  return false;
}

Now i have the problem with updating the partial which is changed. 现在我有更新部分更改的问题。 How can I do this with js? 我该如何使用js?

OK, I get it. 好的我明白了。 The request will be sent in js and no longer triggers the page reload. 该请求将以js发送,并且不再触发页面重新加载。 Using javascript I have edited the checkbox. 使用javascript,我已经编辑了复选框。

Seems to be very similar to this situation: AJAX rails check box using javascript .submit() 似乎与这种情况非常相似: 使用javascript .submit()的AJAX rails复选框

What they do there is redefining the form submission, changing the behavior. 他们在那里所做的是重新定义表单提交,改变了行为。

And as a basic recommendation: use rather unobtrusive JS instead of inlined onchange events 并作为基本建议:使用比较宽松的JS而不是内联的onchange事件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM