AJAX导轨使用JavaScript .submit复选框()导轨、复选框、AJAX、submit

2023-09-10 16:59:25 作者:情深緣淺

我用Rails 3.1,我需要一个复选框来切换,并保存到数据库中,而不在页面刷新或重新定向。

I'm using Rails 3.1 and I need a checkbox to toggle and save to the database without the page refreshing or redirecting.

让我preface说我相当的新手,如果我来了从错误的角度这个问题请让我知道。

Let me preface by saying i'm fairly novice, if i'm coming at this problem from the wrong angle please let me know.

下面是我的表格:

<% form_for book, :remote => true do |f| %>
   <%= f.check_box :finished %>
<% end %>

下面是我的jQuery JavaScript的:

Here is my jQuery javascript:

$('input#book_finished').live("click", function() {
    $(this).parent('form').submit();
});

的:远程=>真实的,当我通过jQuery提交不起作用,但确实,如果我扔在一个提交按钮(这我不能有)。我如何能提交一下,虽然JS的复选框?

The :remote = > true doesn't work when I submit via jQuery, but does if I throw in a submit button (which I can't have). How can I submit on clicking the checkbox though JS?

推荐答案

您code迄今只能通过在复选框中点击处理提交。为了提交通过AJAX的形式,你仍然必须抓住提交事件,prevent默认行为,并发送表单数据:

Your code so far only handles the submitting via a click on the checkbox. In order to submit the form via AJAX, you'll still have to catch the submit event, prevent the default behavior and send the form data:

$('#form-id').submit(function(){
  $.ajax({
    type: this.method,
    url: this.action,
    data: $(this).serialize(),
    success: function(){
      ... // do something in case everything went find
    }
  });
  return false;
});