Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/468.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rails javascript轮询_Javascript_Jquery_Ruby On Rails_Polling - Fatal编程技术网

Rails javascript轮询

Rails javascript轮询,javascript,jquery,ruby-on-rails,polling,Javascript,Jquery,Ruby On Rails,Polling,我试图在我的应用程序中实现javascript轮询,但遇到了一些问题。我非常赞同这一点。我的问题是试图预先准备任何新发现的数据。它会预先处理所有新旧数据,如果没有找到任何新数据,它只会预先处理所有旧数据。我的另一个问题是,我的setTimeout只被调用一次,即使在我尝试像railscast中显示的那样保持轮询之后也是如此。下面是我的代码。我做错了什么 polling.js var InboxPoller; InboxPoller = { poll: function() { re

我试图在我的应用程序中实现javascript轮询,但遇到了一些问题。我非常赞同这一点。我的问题是试图预先准备任何新发现的数据。它会预先处理所有新旧数据,如果没有找到任何新数据,它只会预先处理所有旧数据。我的另一个问题是,我的setTimeout只被调用一次,即使在我尝试像railscast中显示的那样保持轮询之后也是如此。下面是我的代码。我做错了什么

polling.js

var InboxPoller;

InboxPoller = {
  poll: function() {
    return setTimeout(this.request, 5000);
  },
  request: function() {
    return $.getScript($('.inbox_wrap').data('url'), {
      after: function() {
        $('.conversation').last().data('id')
      }
    });
  }
};

$(function() {
  if ($('.inbox_wrap').length > 0) {
    return InboxPoller.poll();
  }
});
polling.js.erb

$(".inbox_wrap").prepend("<%= escape_javascript(render @conversations, :locals => {:conversation => @conversation}) %>");
InboxPoller.poll();
class ConversationsController < ApplicationController
    before_filter :authenticate_member!
    helper_method :mailbox, :conversation

    def index
        @messages_count = current_member.mailbox.inbox({:read => false}).count
        @conversations = current_member.mailbox.inbox.order('created_at desc').page(params[:page]).per_page(15)
    end

    def polling 
        @conversations = current_member.mailbox.inbox.where('conversation_id > ?', params[:after].to_i)
    end 

    def show
        @receipts = conversation.receipts_for(current_member).order('created_at desc').page(params[:page]).per_page(20)

        render :action => :show
        @receipts.mark_as_read 
    end

    def create
        recipient_emails = conversation_params(:recipients).split(',').take(14)
        recipients = Member.where(user_name: recipient_emails).all

        @conversation = current_member.send_message(recipients, *conversation_params(:body, :subject)).conversation

        respond_to do |format|
          format.html { redirect_to conversation_path(conversation) }
          format.js
        end  
    end

    def reply
        @receipts = conversation.receipts_for(current_member).order('created_at desc').page(params[:page]).per_page(20)
        @receipt = current_member.reply_to_conversation(conversation, *message_params(:body, :subject))

        respond_to do |format|
          format.html { conversation_path(conversation) }
          format.js 
        end
    end

    private

      def mailbox
          @mailbox ||= current_member.mailbox
      end

      def conversation
          @conversation ||= mailbox.conversations.find(params[:id])
      end

      def conversation_params(*keys)
          fetch_params(:conversation, *keys)
      end

      def message_params(*keys)
          fetch_params(:message, *keys)
      end

      def fetch_params(key, *subkeys)
          params[key].instance_eval do
            case subkeys.size
              when 0 then self
              when 1 then self[subkeys.first]
              else subkeys.map{|k| self[k] }
            end
          end
      end

      def check_current_subject_in_conversation
          if !conversation.is_participant?(current_member)
            redirect_to conversations_path
          end
      end

end
<%= content_tag :div, class: "inbox_wrap", data: {url: polling_conversations_url} do %>
    <%= render partial: "conversations/conversation", :collection => @conversations, :as => :conversation %>
<% end %>
<div id="conv_<%= conversation.id %>_<%= current_member.id %>" class="conversation" data-id="<%= conversation.id %>">

    <div class="conv_body">
        <%= conversation.last_message.body %>
    </div>

    <div class="conv_time">
        <%= conversation.updated_at.localtime.strftime("%a, %m/%e %I:%M%P") %>
    </div>

</div>
$(“.inbox_wrap”).prepend(“{:conversation=>@conversation})%>”;
InboxPoller.poll();
对话\u controller.rb

$(".inbox_wrap").prepend("<%= escape_javascript(render @conversations, :locals => {:conversation => @conversation}) %>");
InboxPoller.poll();
class ConversationsController < ApplicationController
    before_filter :authenticate_member!
    helper_method :mailbox, :conversation

    def index
        @messages_count = current_member.mailbox.inbox({:read => false}).count
        @conversations = current_member.mailbox.inbox.order('created_at desc').page(params[:page]).per_page(15)
    end

    def polling 
        @conversations = current_member.mailbox.inbox.where('conversation_id > ?', params[:after].to_i)
    end 

    def show
        @receipts = conversation.receipts_for(current_member).order('created_at desc').page(params[:page]).per_page(20)

        render :action => :show
        @receipts.mark_as_read 
    end

    def create
        recipient_emails = conversation_params(:recipients).split(',').take(14)
        recipients = Member.where(user_name: recipient_emails).all

        @conversation = current_member.send_message(recipients, *conversation_params(:body, :subject)).conversation

        respond_to do |format|
          format.html { redirect_to conversation_path(conversation) }
          format.js
        end  
    end

    def reply
        @receipts = conversation.receipts_for(current_member).order('created_at desc').page(params[:page]).per_page(20)
        @receipt = current_member.reply_to_conversation(conversation, *message_params(:body, :subject))

        respond_to do |format|
          format.html { conversation_path(conversation) }
          format.js 
        end
    end

    private

      def mailbox
          @mailbox ||= current_member.mailbox
      end

      def conversation
          @conversation ||= mailbox.conversations.find(params[:id])
      end

      def conversation_params(*keys)
          fetch_params(:conversation, *keys)
      end

      def message_params(*keys)
          fetch_params(:message, *keys)
      end

      def fetch_params(key, *subkeys)
          params[key].instance_eval do
            case subkeys.size
              when 0 then self
              when 1 then self[subkeys.first]
              else subkeys.map{|k| self[k] }
            end
          end
      end

      def check_current_subject_in_conversation
          if !conversation.is_participant?(current_member)
            redirect_to conversations_path
          end
      end

end
<%= content_tag :div, class: "inbox_wrap", data: {url: polling_conversations_url} do %>
    <%= render partial: "conversations/conversation", :collection => @conversations, :as => :conversation %>
<% end %>
<div id="conv_<%= conversation.id %>_<%= current_member.id %>" class="conversation" data-id="<%= conversation.id %>">

    <div class="conv_body">
        <%= conversation.last_message.body %>
    </div>

    <div class="conv_time">
        <%= conversation.updated_at.localtime.strftime("%a, %m/%e %I:%M%P") %>
    </div>

</div>
类会话控制器false}).count
@对话=当前成员.邮箱.收件箱.订单('created_at desc')。页面(参数[:页面])。每页(15)
结束
def轮询
@conversations=当前成员.mailbox.inbox.where('conversations\u id>?',参数[:after].\u i)
结束
def秀
@收据=对话。当前成员的收据。订单('created_at desc')。页面(参数[:page])。每页(20)
呈现:操作=>:显示
@收据。标记为已读
结束
def创建
收件人电子邮件=对话参数(:收件人)。拆分(',')。获取(14)
收件人=成员。其中(用户名:收件人电子邮件)。全部
@对话=当前成员。发送消息(收件人,*对话参数(:正文,:主题))。对话
回应待办事项|格式|
format.html{重定向到对话路径(对话)}
format.js
结束
结束
def回复
@收据=对话。当前成员的收据。订单('created_at desc')。页面(参数[:page])。每页(20)
@接收=当前成员。回复对话(对话,*消息参数(:正文,:主题))
回应待办事项|格式|
format.html{conversation_path(conversation)}
format.js
结束
结束
私有的
def邮箱
@邮箱| |=当前成员。邮箱
结束
def对话
@对话| |=邮箱.对话.查找(参数[:id])
结束
def对话参数(*键)
获取参数(:对话,*键)
结束
def消息参数(*键)
获取参数(:消息,*键)
结束
def fetch_参数(键,*子键)
参数[key]。实例\u评估do
大小写子键
当0时,则为self
当1时,则为self[子键.first]
else子键.map{| k | self[k]}
结束
结束
结束
def检查对话中的当前主题
如果!对话。是否参与?(当前成员)
重定向到对话路径
结束
结束
结束
index.html.erb

$(".inbox_wrap").prepend("<%= escape_javascript(render @conversations, :locals => {:conversation => @conversation}) %>");
InboxPoller.poll();
class ConversationsController < ApplicationController
    before_filter :authenticate_member!
    helper_method :mailbox, :conversation

    def index
        @messages_count = current_member.mailbox.inbox({:read => false}).count
        @conversations = current_member.mailbox.inbox.order('created_at desc').page(params[:page]).per_page(15)
    end

    def polling 
        @conversations = current_member.mailbox.inbox.where('conversation_id > ?', params[:after].to_i)
    end 

    def show
        @receipts = conversation.receipts_for(current_member).order('created_at desc').page(params[:page]).per_page(20)

        render :action => :show
        @receipts.mark_as_read 
    end

    def create
        recipient_emails = conversation_params(:recipients).split(',').take(14)
        recipients = Member.where(user_name: recipient_emails).all

        @conversation = current_member.send_message(recipients, *conversation_params(:body, :subject)).conversation

        respond_to do |format|
          format.html { redirect_to conversation_path(conversation) }
          format.js
        end  
    end

    def reply
        @receipts = conversation.receipts_for(current_member).order('created_at desc').page(params[:page]).per_page(20)
        @receipt = current_member.reply_to_conversation(conversation, *message_params(:body, :subject))

        respond_to do |format|
          format.html { conversation_path(conversation) }
          format.js 
        end
    end

    private

      def mailbox
          @mailbox ||= current_member.mailbox
      end

      def conversation
          @conversation ||= mailbox.conversations.find(params[:id])
      end

      def conversation_params(*keys)
          fetch_params(:conversation, *keys)
      end

      def message_params(*keys)
          fetch_params(:message, *keys)
      end

      def fetch_params(key, *subkeys)
          params[key].instance_eval do
            case subkeys.size
              when 0 then self
              when 1 then self[subkeys.first]
              else subkeys.map{|k| self[k] }
            end
          end
      end

      def check_current_subject_in_conversation
          if !conversation.is_participant?(current_member)
            redirect_to conversations_path
          end
      end

end
<%= content_tag :div, class: "inbox_wrap", data: {url: polling_conversations_url} do %>
    <%= render partial: "conversations/conversation", :collection => @conversations, :as => :conversation %>
<% end %>
<div id="conv_<%= conversation.id %>_<%= current_member.id %>" class="conversation" data-id="<%= conversation.id %>">

    <div class="conv_body">
        <%= conversation.last_message.body %>
    </div>

    <div class="conv_time">
        <%= conversation.updated_at.localtime.strftime("%a, %m/%e %I:%M%P") %>
    </div>

</div>

@对话,:as=>:对话%>
\u conversation.html.erb

$(".inbox_wrap").prepend("<%= escape_javascript(render @conversations, :locals => {:conversation => @conversation}) %>");
InboxPoller.poll();
class ConversationsController < ApplicationController
    before_filter :authenticate_member!
    helper_method :mailbox, :conversation

    def index
        @messages_count = current_member.mailbox.inbox({:read => false}).count
        @conversations = current_member.mailbox.inbox.order('created_at desc').page(params[:page]).per_page(15)
    end

    def polling 
        @conversations = current_member.mailbox.inbox.where('conversation_id > ?', params[:after].to_i)
    end 

    def show
        @receipts = conversation.receipts_for(current_member).order('created_at desc').page(params[:page]).per_page(20)

        render :action => :show
        @receipts.mark_as_read 
    end

    def create
        recipient_emails = conversation_params(:recipients).split(',').take(14)
        recipients = Member.where(user_name: recipient_emails).all

        @conversation = current_member.send_message(recipients, *conversation_params(:body, :subject)).conversation

        respond_to do |format|
          format.html { redirect_to conversation_path(conversation) }
          format.js
        end  
    end

    def reply
        @receipts = conversation.receipts_for(current_member).order('created_at desc').page(params[:page]).per_page(20)
        @receipt = current_member.reply_to_conversation(conversation, *message_params(:body, :subject))

        respond_to do |format|
          format.html { conversation_path(conversation) }
          format.js 
        end
    end

    private

      def mailbox
          @mailbox ||= current_member.mailbox
      end

      def conversation
          @conversation ||= mailbox.conversations.find(params[:id])
      end

      def conversation_params(*keys)
          fetch_params(:conversation, *keys)
      end

      def message_params(*keys)
          fetch_params(:message, *keys)
      end

      def fetch_params(key, *subkeys)
          params[key].instance_eval do
            case subkeys.size
              when 0 then self
              when 1 then self[subkeys.first]
              else subkeys.map{|k| self[k] }
            end
          end
      end

      def check_current_subject_in_conversation
          if !conversation.is_participant?(current_member)
            redirect_to conversations_path
          end
      end

end
<%= content_tag :div, class: "inbox_wrap", data: {url: polling_conversations_url} do %>
    <%= render partial: "conversations/conversation", :collection => @conversations, :as => :conversation %>
<% end %>
<div id="conv_<%= conversation.id %>_<%= current_member.id %>" class="conversation" data-id="<%= conversation.id %>">

    <div class="conv_body">
        <%= conversation.last_message.body %>
    </div>

    <div class="conv_time">
        <%= conversation.updated_at.localtime.strftime("%a, %m/%e %I:%M%P") %>
    </div>

</div>

Javascript轮询效率极低-基本上每隔几秒钟向服务器发送请求以侦听“更新”。即使如此,在许多情况下,更新将是完整的文件/批数据,没有简洁性

如果我们不得不这样做,我们总是会考虑使用一种更有效的技术,特别是
SSE
Websockets

--

苏格兰和南方能源公司

var InboxPoller;

InboxPoller = {
  poll: function() {
    return setTimeout(this.request, 5000);
  },
  request: function() {
    return $.getScript($('.inbox_wrap').data('url'), {
      after: function() {
        $('.conversation').last().data('id')
      }
    });
  }
};

$(function() {
  if ($('.inbox_wrap').length > 0) {
    return InboxPoller.poll();
  }
});
您是否考虑过使用
服务器发送事件

这是一个与Javascript轮询非常相似的方法,每几秒钟发送一次请求。不同之处在于它们的基本工作方式——收听自己的“频道”(mime类型
文本/事件流
——允许您对发送的数据进行真正的特定处理)

你可以这样称呼它:

#app/assets/javascript/application.js
var source = new EventSource("your/controller/endpoint");
source.onmessage = function(event) {
    console.log(event.data);
};
这将允许您为“事件侦听器”创建一个:

您可以使用类发送更新:

#app/controllers/your_controller.rb
类YourController
--

WebSocket

var InboxPoller;

InboxPoller = {
  poll: function() {
    return setTimeout(this.request, 5000);
  },
  request: function() {
    return $.getScript($('.inbox_wrap').data('url'), {
      after: function() {
        $('.conversation').last().data('id')
      }
    });
  }
};

$(function() {
  if ($('.inbox_wrap').length > 0) {
    return InboxPoller.poll();
  }
});
执行此操作的首选方法是使用
websockets

WebSocket比SSE或标准JS轮询效率更高,因为它们保持连接永久打开。这意味着您可以发送/接收所需的任何更新,而无需向服务器发送持续更新

WebSocket的问题在于设置过程——在自己的应用服务器上运行WebSocket连接非常困难,因此许多人不这么做


如果您对websocket感兴趣,您可能希望研究使用-一个有经验的第三方websocket提供商。我们经常使用这种方法-这是在应用程序中提供“实时”更新的一种非常有效的方法,而且不,我与他们没有任何关系

Javascript轮询效率极低-基本上每隔几秒钟向服务器发送请求以侦听“更新”。即使如此,在许多情况下,更新将是完整的文件/批数据,没有简洁性

如果我们不得不这样做,我们总是会考虑使用一种更有效的技术,特别是
SSE
Websockets

--

苏格兰和南方能源公司

var InboxPoller;

InboxPoller = {
  poll: function() {
    return setTimeout(this.request, 5000);
  },
  request: function() {
    return $.getScript($('.inbox_wrap').data('url'), {
      after: function() {
        $('.conversation').last().data('id')
      }
    });
  }
};

$(function() {
  if ($('.inbox_wrap').length > 0) {
    return InboxPoller.poll();
  }
});
您是否考虑过使用
服务器发送事件