[英]Rails ajax form submit
这是我的布局,全部在authors_controller
和Author
模型中。
index.html.erb
<div class="row">
<div id="author-index" class="col-md-5">
<%= render 'index'%>
</div>
<div id="author-modal" class="modal fade" role="dialog"></div>
</div>
_index.html.erb
<div class="row">
<%= form_tag authors_path, :method => 'get', remote: true do %>
<%= hidden_field_tag :direction, params[:direction]%>
<%= hidden_field_tag :sort, params[:sort]%>
<p>
<%= link_to "New Author", new_author_path, remote: true, class: "btn btn-primary"%>
Search for Author
<%= text_field_tag :search, params[:search], onchange: "$(this).parent('form').submit();"%>
</p>
<% end %>
</div>
<div id="indexTable" class="row">
#contains a table
</div>
我的控制器的表演动作:
def index
@authors = Author.search(params[:search]).order(sort_column + " " + sort_direction).paginate(:per_page => 10, :page => params[:page])
respond_to do |format|
format.html{}
format.js{}
end
end
当我查看服务器的日志时,一切正常
开始GET“ / authors?utf8 =%E2%9C%93&direction =&sort =&search = Ali”
由AuthorsController#index作为JS处理
参数:{“ utf8” =>“✓”,“ direction” =>“”,“ sort” =>“”,“ search” =>“ Ali”}
作者负载(0.1ms)SELECT
authors
。* FROMauthors
WHERE(first_name LIKE'%Ali%'或last_name LIKE'%Ali%')LIMIT 10 OFFSET 0呈现的authors / _index.html.erb(2.3ms)
呈现的authors / index.js.erb(3.2ms)
7ms内完成200 OK(查看:5.2ms | ActiveRecord:0.1ms)
但是页面不会改变。 当我没有远程操作时,表单工作正常:是的。
您应该将一个名为index
的js.erb
模板添加到authors views文件夹(app / views / authors / index.js.erb)中。 执行Ajax调用时,此模板应具有要执行的javascript代码(将在客户端发送和评估)。 或多或少:
$("#author-index").html("<%= j(render 'index').html_safe %>")
注意format.js
在respond_to
块; 允许控制器响应您的Ajax请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.