2016-01-12 50 views
0

我有一個活動作業表,顯示所有活動作業。我試圖在表格中添加搜索功能,但我的表格數據沒有渲染到表格中。這是我迄今爲止的代碼。Ruby On Rails - 使用jquery更新表格獲取請求

資產/ 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"); 

我的控制器有一個叫做搜索方法

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,該表從未以任何方式更新或更改。如果你可以請這個問題的幫助,我一定會很感激。提前致謝!

回答

1

你告訴ajax調用期望json作爲返回,但你實際上是返回一個JS腳本。嘗試:

$.ajax({ 
    type: 'get', 
    url: '/jobs/' + $('#search').val() + '/search', 
    dataType: 'script', 
    async: true 
}); 
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");