2017-02-28 91 views
2

好的,我正在尋找的是一種獲取ajax腳本以在頁面的背景中運行並查看數據庫中是否存在新記錄並且如果有抓取記錄並顯示在我的網頁上。Ruby on rails live update

我也不想使用插件我寧願做我自己,因爲我喜歡學習如何做到這一點,更容易做出改變,如果我需要的東西在未來不同

IM很新AJAX和Ruby on Rails所以有點解釋的,可能是爲了

這是我的控制器目前在IA用戶更新它的更改,而該頁面的內容令人耳目一新,但我想它是什麼也得到了新的數據

class NotificationsController < ApplicationController 

    # GET /notifications 
    # GET /notifications.json 
    def index 
    @notifications = Notification.all 
    end 

def show 
    end 

def update 
    @notification = Notification.find(params[:id]) 
    @notification.update_attributes(:content => params[:content][:content]) 
    respond_to do |format| 
    format.html { redirect_to notifications_path } 
    format.json { render json: @notification} 
    end 
end 
end 

這是js fil Ë

$(document).ready(function(){ 
    $('input[type=submit]').on('click', function(event){ 

     var form = $(this).parent('form'); 
     event.preventDefault(); 

     $.ajax({ 
      type:"POST", 
      url: form.attr('action'), 
      data: form.serialize(), 
      success: function(data){ 
      console.log('this worked') 
      $('#'+ data.id).html(data.content) 

         }, 
      error: function(data){ 
       console.log('failed') 
      }, 
      dataType: 'JSON' 
     }); 
     }); 
    }); 

,這是因爲你可以告訴我還沒有做創建操作我的html文件

<% content_for :titleheader do %> 
NOTIFICATIONS 
<% end %> 

<h1>Listing Notifications</h1> 

    <% @notifications.each do |notification| %> 
    <%= form_for notification do |f| %> 

    <%= notification.id %> 
    <div id="<%= notification.id %>"><%=notification.content %></div> 
    <%= notification.read %> 

<%= text_field "content", "content" %> 
    <%= f.submit "change status" %> 
<% end %> 
<% end %> 

因爲IM不知道如果我將不得不通過Ajax或東西要做到這一點

幫助是非常讚賞

+0

這是一個壞問題或者沒有人知道答案? – Ray

回答

0

是的,你需要使用一個名爲輪詢過程中,通過AJAX來做到這一點。不幸的是,如果你不想使用任何額外的寶石或插件,那麼這是唯一的「簡單」解決方案。輪詢是指腳本定期檢查服務器是否有更新。

setInterval(function(){ ajax_check_and_apply_updates_function(); }, 10000); 

將運行您的AJAX檢查每10秒更新。

如果您願意開放寶石,您可以使用FayePusher來實現異步。

如果有人知道在rails和AJAX上只是ruby的異步方式,我真的希望他們告訴我們,因爲那會是塗料。