weixin_33711641 2014-04-09 17:27 采纳率: 0%
浏览 19

Rails Ajax表单提交

This is my layout, all in the authors_controller and Author model.

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"

Processing by AuthorsController#index as JS

Parameters: {"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

Rendered authors/_index.html.erb (2.3ms)

Rendered authors/index.js.erb (3.2ms)

Completed 200 OK in 7ms (Views: 5.2ms | ActiveRecord: 0.1ms)

However the page does not change. The form worked fine when I do it without remote: true.

  • 写回答

1条回答 默认 最新

  • ?Briella 2014-04-09 17:47
    关注

    You should add a js.erb template named index into authors views folder (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. More or less:

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

    Notice the format.js in the respond_to block; that allows the controller to respond to your Ajax request.

    评论

报告相同问题?

悬赏问题

  • ¥60 QQOP数据,什么是op数据号,怎么提取op数据!能不能大量提取(语言-c语言)
  • ¥15 matlab代码 关于微分方程和嵌套的分段函数。
  • ¥15 把VMware项目复制到另一台电脑
  • ¥15 onlyoffice编辑完后立即下载,下载的不是最新编辑的文档
  • ¥15 求caverdock使用教程
  • ¥15 Coze智能助手搭建过程中的问题请教
  • ¥15 12864只亮屏 不显示汉字
  • ¥20 三极管1000倍放大电路
  • ¥15 vscode报错如何解决
  • ¥15 前端vue CryptoJS Aes CBC加密后端java解密