通过Ajax提交表单后,“提交”按钮被冻结

时间:2019-03-31 13:31:37

标签: javascript jquery ruby-on-rails ajax

当我在ROR中使用jQuery-Ajax提交表单时,提交按钮被冻结。 我正在练习GitHub提供的"Integrating Ajax and Rails: A Simple Todo List App"

class TodosController < ApplicationController
    def create
        #binding.pry
        @todo = Todo.create(todo_params)

        respond_to do |format|
            format.html {redirect_to home_path}
            format.js {}
        end
    end

    private

    def todo_params
        params.require(:todo).permit(:description, :priority)
    end
end

index.html.erb

<h2>Create Todos</h2>
<%= render 'new' %>

<h2>Todos List</h2>
<ul>
    <%= render @todos %>
</ul>

_new.html.erb

<%= form_for Todo.new, html: {id: "form1"} do |f| %>
<p>
    <%= f.label :description %>
    <%= f.text_field :description %>
</p>
<p>
    <%= f.label :priority %>
    <%= f.text_field :priority %>
</p>
<p>
    <%= f.submit 'Submit' %>
</p>
<% end %>

_todo.html.erb

<li>
    <%= todo.description %><br>
    <strong>Priority:</strong><%= todo.priority %><br>
    <%= link_to 'done', todo_path(todo) , method: 'delete' %>
</li>

create.js.erb

$("ul").append("<%= j render partial: 'todo', locals: {todo: @todo} %>");

app / assets / javascript / todos.js

$(function(){
    $("#form1").submit(function(event){
    event.preventDefault();

    let method = $(this).attr('method');
    let action = $(this).attr('action');
    let description = $(this).find('#todo_description').val();
    let priority = $(this).find('#todo_priority').val();
    let data = $(this).serializeArray();

    $.ajax({
        method: method,
        url: action,
        data: data,

        dataType: 'script'
    });
  });
});

1 个答案:

答案 0 :(得分:0)

该按钮被冻结,因为现在有一个jquery脚本将其禁用,以防止多次提交。单击单击时,检查是否有任何添加到“提交”按钮中的类/属性,然后将一些jquery放入您的create.js.erb中以将其删除,并在要提交新的待办事项时清除字段。