Rails 3 AJAX solution for updating tables?

后端 未结 2 1610
刺人心
刺人心 2021-02-14 21:32

I know this is a popular topic, but I\'ve been searching quite a bit trying to find the answer and strangely haven\'t found anything that has been able to help...

I\'ve

相关标签:
2条回答
  • 2021-02-14 21:50

    First create a rails endpoint that can get the new entries:

    # config/routes.rb
    match '/records/new_since/:time', :to => 'records#new_since'
    
    # app/controllers/records_controller.rb
    class RecordsController < ApplicationController
      def new_since 
        @records = Record.where('created_at > ?', Time.parse(params[:time]))
        respond_to do |format|
          format.json do
           @records[:time] = Time.now.to_s(:db)
           render :json => @records.to_json
          end
        end
      end
    end
    

    Then, a little javascript on the client side (prototype here):

    setInterval(
      function(){
        new Ajax.Request('/records/new_since/' + $('time') + '.json', {
          method: 'get',
          onSuccess: function(transport){
            var records = transport.response.responseJSON;
            // insert the last checked time into <div id='time'></div>
            $('time').innerHTML = records.time;
            // loop over response JSON and do what you want with the data
            records.each(function(record){
              $$('table#records').insert({
                bottom: '<tr><td>'+record.attribute+'</td></tr>';
              });
            });
          }
        });
      },
      30000
    );
    

    Alternately, instead of sending down json, you can render a template of all the new table rows, and just throw that in too. Less flexible, but a little simpler if you just want to throw the responses at the bottom:

    def new_since
      @records = Record.where('created_at > ?', Time.parse(params[:time]))
      respond_to do |format|
        format.json {} # renders json template
      end
    end
    
    # app/views/records/new_since.html.json.erb
    <% records.each do |record| %>
      <tr><td><%= record.attribute %></td></tr>
    <% end %>
    
    setInterval(
      function(){
        new Ajax.Request('/records/new_since/' + $('time') + '.json', {
          method: 'get',
          onSuccess: function(transport){
            var record_rowss = transport.response.responseText;
            $('time').innerHTML = records.time;
            $$('table#records').insert({bottom: record_rows});
          }
        });
      },
      30000
    );
    
    0 讨论(0)
  • 2021-02-14 21:53

    How is this?

    http://www.datatables.net/

    another whole set are here:

    http://plugins.jquery.com/plugin-tags/ajax-table

    Sometimes it's better to use what's there than to build new.

    But to answer your question, it depends on whether you are manipulating the DOM yourself or letting Prototype, jQuery, MooTools, or whatever do the heavy lifting. The idea is to set a timer in your Javascript and when the timer fires, ask the server for updates. The server -- your Rails app -- will package up whatever has changed and send it back.

    Step 1: Decide on a framework. I use jQuery but most will do.

    Step 2: Decide on a data format. I use JSON, but XML will do.

    Step 3: Set up the timer loop. It involves using settimer() and resetting it after each observation.

    Step 4: In the handler that executes when the timer fires, package up a "last seen" timestamp and make the Ajax request. How you do it varies from framework to framework -- or if you are coding right to the DOM, from browser to browser.

    Step 5: Set up a "success" handler so that when your server returns zero or more rows of data, you can insert these TR-TD-/TD-/TR rows in your table.

    Step 6: Update any internal junk like number or row counters or whatever else your Javascript is tracking.

    Note: You may find there are plugins other people have written that will work great and save you the trouble, but you should have a basic understanding of how this is done.

    0 讨论(0)
提交回复
热议问题