我是 Rails 的新手(来自 PHP)并且在使用 ajax 提交表单时遇到了问题。基本上,我有一个任务列表,当添加一个新任务时,我希望将新任务 append 到列表中。表单本身正在提交,但我不知道如何 append 新条目。提前致谢!
表格
<%= simple_form_for(Task.new) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :name %>
<%= f.input :date_due %>
<%= f.input :phase_id, :as => :hidden, :input_html => { :value => @phase.id } %>
<%= f.input :status, :as => :hidden, :input_html => { :value => "0" } %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
JS
$('form#new_task').submit(function() {
var valuesToSubmit = $(this).serialize();
$.ajax({
type: "POST",
url: $(this).attr('action'), //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON"
}).success(function(data){
// disaply new charge in the table
$('body').append(data);
// clear the form
$("input#task_name").val('');
//focus on the input again
$("input#task_name").focus();
});
return false; // prevents normal behaviour
});
编辑 还值得一提的是,这是在“阶段”的 View 中发生的。每个阶段都有_许多任务,每个任务属于_一个阶段。
最佳答案
看起来 Controller 正在返回 JSON。您需要将返回的 JSON 包装在 html 中,语法与您要 append 到的表中其他行的语法相同(可能是 <tr><td>..</td></tr>
),然后将该 html append 到表中。或者,您可以为表中的每一行制作一个部分,当您添加新任务时,从 Controller 返回部分的 html,然后将其 append 到表中。
<table id="tasks">
<% @phase.tasks.each do |task| %>
<%= render :partial => 'task_row', :locals => {:task => task} %>
<% end %>
</table>
将 js 更改为:
$('form#new_task').submit(function() {
var valuesToSubmit = $(this).serialize();
$.ajax({
type: "POST",
url: $(this).attr('action'), //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "HTML"
}).success(function(data){
// disaply new charge in the table
$('#tasks').append(data);
// clear the form
$("input#task_name").val('');
//focus on the input again
$("input#task_name").focus();
});
return false; // prevents normal behaviour
});
在你的 Controller 中是这样的
def create
@task = Task.new(params[:task])
respond_to do |format|
if @task.save
format.js{render :partial => 'tasks', :locals => {:task > @task} }
else
#handle validation error
end
end
end
这一切都未经测试,但我希望它能让你走上正轨
关于jquery - 带有 jquery $.ajax 的 Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13352313/