简体   繁体   English

Rails Ajax表单提交

[英]Rails ajax form submit

This is my layout, all in the authors_controller and Author model. 这是我的布局,全部在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>

My controller's show action: 我的控制器的表演动作:

    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

When I look at the log of my server, all should work fine 当我查看服务器的日志时,一切正常

Started GET "/authors?utf8=%E2%9C%93&direction=&sort=&search=Ali" 开始GET“ / authors?utf8 =%E2%9C%93&direction =&sort =&search = Ali”

Processing by AuthorsController#index as JS 由AuthorsController#index作为JS处理

Parameters: {"utf8"=>"✓", "direction"=>"", "sort"=>"", "search"=>"Ali"} 参数:{“ utf8” =>“✓”,“ direction” =>“”,“ sort” =>“”,“ search” =>“ Ali”}

Author Load (0.1ms) SELECT authors .* FROM authors WHERE (first_name LIKE '%Ali%' OR last_name LIKE '%Ali%') LIMIT 10 OFFSET 0 作者负载(0.1ms)SELECT authors 。* FROM authors WHERE(first_name LIKE'%Ali%'或last_name LIKE'%Ali%')LIMIT 10 OFFSET 0

Rendered authors/_index.html.erb (2.3ms) 呈现的authors / _index.html.erb(2.3ms)

Rendered authors/index.js.erb (3.2ms) 呈现的authors / index.js.erb(3.2ms)

Completed 200 OK in 7ms (Views: 5.2ms | ActiveRecord: 0.1ms) 7ms内完成200 OK(查看:5.2ms | ActiveRecord:0.1ms)

However the page does not change. 但是页面不会改变。 The form worked fine when I do it without remote: true. 当我没有远程操作时,表单工作正常:是的。

You should add a js.erb template named index into authors views folder (app/views/authors/index.js.erb). 您应该将一个名为indexjs.erb模板添加到authors views文件夹(app / views / authors / index.js.erb)中。 This template should have the javascript code that you want to execute (will be sent and evaluated on the client side) when the Ajax call is performed. 执行Ajax调用时,此模板应具有要执行的javascript代码(将在客户端发送和评估)。 More or less: 或多或少:

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

Notice the format.js in the respond_to block; 注意format.jsrespond_to块; that allows the controller to respond to your Ajax request. 允许控制器响应您的Ajax请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM