Ruby On Rails - 使用Jquery获取请求更新表

时间:2016-01-12 01:45:49

标签: ruby-on-rails

我有一个显示所有活动作业的活动作业表。我试图在表上添加搜索功能,但我的表数据不会呈现给表。这是我到目前为止的代码。

资产/ Javascript角/ jobs.js

$(document).ready(function(){
    $("#search").keypress(function(){
       $.ajax({
            type : 'get',
            url : "/jobs/"+$('#search').val()+"/search",    
            dataType : 'json',
            async : true,
            success : function(data) {

            }
          });
    });
});

我的active_jobs.html.erb视图呈现了一个名为_job.html.erb的部分

<tr>
    <td><%= job.id %></td>
    <td><%= job.customer.name %></td>
    <td><%= job.customer.email %></td>
    <td><%= job.customer.phone_one %></td>
    <td><%= job.status %></td>
</tr>

我的active_jobs.html.erb视图

<h1>Jobs</h1>
<input id="search" type="text" name="Search"><br>
<table id="jobs-table" class="table table-bordered">
    <tr>
        <th>ID</th> 
        <th>Name</th> 
        <th>Phone</th> 
        <th>Email</th> 
        <th>Status</th> 
    </tr>   
    <tbody>
        <%= render @jobs %>
    </tbody>

这是我的show.js.erb用于呈现对表的响应(不会正确更新表,什么都不做。)

 $("<%= escape_javascript(render @jobs) %>").appendTo("#jobs-table");

我的控制器有一个名为search

的方法
def search
    @jobs = Job.where(id: params[:keyword])
    respond_to do |format|
        format.html {redirect_to customers_url}
        format.js {render :action => "show"}
    end
end

这是我的控制台

Started GET "/jobs/2/search" for 10.0.2.2 at 2016-01-12 01:42:15 +0000
Cannot render console from 10.0.2.2! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255

Processing by JobsController#search as JSON
Parameters: {"keyword"=>"2"}
Job Load (1.0ms)  SELECT "jobs".* FROM "jobs" WHERE "jobs"."id" = ?  [["id", 2]]
 Customer Load (0.9ms)  SELECT  "customers".* FROM "customers" WHERE "customers"."id" = ? LIMIT 1  [["id", 2]]
Rendered jobs/_job.html.erb (2.1ms)
Rendered jobs/show.js.erb (24.1ms)
Completed 200 OK in 89ms (Views: 86.6ms | ActiveRecord: 1.9ms)

所有原始数据(在页面加载/刷新时)加载都很好,但是当我开始通过get请求搜索id时,表永远不会以任何方式更新或更改。如果你能帮忙解决这个问题,我一定会很感激。提前谢谢!

2 个答案:

答案 0 :(得分:1)

你告诉ajax调用期望json作为返回,但你实际上是在返回一个JS脚本。尝试:

$.ajax({
    type: 'get',
    url: '/jobs/' + $('#search').val() + '/search',
    dataType: 'script',
    async: true
});

答案 1 :(得分:0)

执行以下操作:

#config/routes.rb
resources :jobs do
   get "search(/:keyword)", action: :show, on: :collection #-> url.com/jobs/search?keyword=query || url.com/jobs/search/:keyword
end

#app/assets/javascripts/application.js
$(document).on("keypress", "#search", function(e) {
   $.get("jobs/search", {keyword: $('#search').val()});
});

#app/controllers/jobs_controller.rb
class JobsController < ApplicationController
   def show
      if params[:keyword]
         @jobs = Job.where id: params[:keyword]
      else
         @job = Job.find params[:id]
      end

      respond_to do |format|
          format.js 
          format.html {redirect_to customers_url}
      end
   end
end

#app/views/jobs/show.js.erb
("<%=j render @jobs %>").appendTo("#jobs-table");