0

I have an application that depends on making web service calls in its controller to fetch data. I want to add a feature where the page automatically refreshes the content, that is calls the action based on some set period of time. I've found many posts that hint around my problem, and I have tried setInterval which, puzzling to me, fired twice for every update. Here is the code for that:

$(document).ready(
  function(){
    var loader = function(){
      $('.container').load('/dashboard/index');
    };
    setInterval(loader, 3000);
  });

I get the feeling this is an ajax issue, but I don't have a trigger event to signal the update. Any help is appreciated.

My Controller code:

class DashboardController < ApplicationController
  include ActionView::Helpers::NumberHelper
  include FakeMaker

  def index
    @reports = fake_maker("report", 22)
    @workstations = fake_maker("workstation", 8)
    @data_sources = fake_maker("data_source", 2)
  end
end

The FakeMaker class

module FakeMaker
  SOURCE_A = "A"
  SOURCE_B = "B"
  TYPES_A = Faker::Lorem.words(num = 10)
  TYPES_B = Faker::Lorem.words(num = 4)

  def fake_maker(type, count)
    fake = []
    case type
    when "report"
      count.times { fake << fake_report }
    when "workstation"
      count.times { fake << fake_workstation }
    when "data_source"
      fake = fake_data_source
    end
    fake
  end

  def fake_report
    report = { source: [SOURCE_A, SOURCE_B].sample,
               count: number_with_delimiter(Faker::Number.number(5), :delimiter => ',') }
    report[:type] = report[:source] == SOURCE_A ? TYPES_A.sample : TYPES_B.sample.capitalize
    report
  end

  def fake_workstation
    { name: Faker::Lorem.word,
      downloaded: number_with_delimiter(Faker::Number.number(3), :delimiter => ','),
      available: number_with_delimiter(Faker::Number.number(5), :delimiter => ','),
      last_connect: Random.rand(10.weeks).ago.strftime("%Y-%m-%d %H:%M:%S") }
  end

  def fake_data_source
    data_sources = []
    ["A", "B"].each do |source|
      data_sources << { type: source,
                        name: Faker::Internet.url,
                        status: ["UP", "DOWN"].sample }
    end
    data_sources
  end
end
4

1 回答 1

1

Can you try it this way

$(document).ready(
  function(){
    setInterval(function(){
       $('.container').load('/dashboard/index');
    }, 3000);
  });
于 2013-09-11T23:39:47.317 回答