Rails ajax表单提交

Rails ajax form submit

本文关键字:表单提交 ajax Rails      更新时间:2023-09-26

这是我的布局,都在authors_controllerAuthor模型中。

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"/作者?utf8=%E2%9C%93&方向=&排序=&search=Ali";

AuthorsController#索引作为JS 进行处理

参数:{"utf8"="gt;";✓&"方向"=>quot&"排序"=>quot&"搜索"=>quot;阿里

Author Load(0.1ms)SELECT authors.*FROM authors WHERE(first_name LIKE'%Ali%'或last_name LIKE[%Ali%')LIMIT 10 OFFSET 0

呈现的作者/_index.html.erb(2.3ms)

呈现的作者/index.js.erb(3.2ms)

在7ms内完成200 OK(视图:5.2ms |活动记录:0.1ms)

但是页面不会更改。当我在没有遥控器的情况下完成时,表单运行良好:是的。

您应该将名为indexjs.erb模板添加到authors视图文件夹(app/views/authors/index.js.erb)中。此模板应该包含执行Ajax调用时要执行的javascript代码(将在客户端发送并评估)。或多或少:

$("#author-index").html("<%= j(render 'index').html_safe %>")

注意respond_to块中的format.js;它允许控制器响应您的Ajax请求。