복붙노트

[RUBY-ON-RAILS] Ajax를 사용하여 자주 부분 새로 고침이 가능 있습니까?

RUBY-ON-RAILS

Ajax를 사용하여 자주 부분 새로 고침이 가능 있습니까?

배경, 나는 다시로드와 쇼에 많은 읽지 않은 메시지가 얼마나 수를 원하는. 내가 페이지를 새로 고치지 않고 그것을 원하지. 나는 아약스를 사용하는 것을 의미한다.

나는 메뉴에이 있었다면, 어떻게에만이 섹션 매 30 초를 새로 고칠 수 있습니다?

<li><%= link_to sanitize('<i class="icon-envelope"></i> ') + "received messages" + sanitize(' <span class="badge badge-info">'+current_user.mailbox.inbox(:read => false).count(:id, :distinct => true).to_s+'</span>'), messages_received_path  %></li>

messages_controller.rb

  def received
    if params[:search]
     @messages = current_user.mailbox.inbox.search_messages(@search).page(params[:page]).per(10)
    else
     @messages = current_user.mailbox.inbox.page(params[:page]).per(10)
    end 
     add_crumb 'Messages Received', messages_received_path

     @box = 'inbox'
     render :index
  end

최신 정보:_______________________________

자산 / 자바 스크립트 / refresh_messages_count.js

$(document).ready(function () {
    // will call refreshPartial every 3 seconds
    setInterval(refreshPartial, 3000)

});

function refreshPartial() {
  $.ajax({
    url: "messages/refresh_part";
 })
}

messages_controller.rb

def refresh_part
    @message_count = current_user.mailbox.inbox(:read => false).count(:id, :distinct => true)

    # get whatever data you need to a variable named @data 
    respond_to do |format| 
        format.js {render :action=>"refresh_part.js"} 
    end

end

전경 / 레이아웃 / _menu.html.erb

<span id="message_received_count"><%= render :partial => "layouts/message_received_count" %></span>

전경 / 레이아웃 / _message_received_count.html.erb

<% if user_signed_in? && current_user.mailbox.inbox(:read => false).count(:id, :distinct => true) > 0 %>
 <li><%= link_to sanitize('<i class="icon-envelope"></i> ') + "Received" + sanitize(' <span class="badge badge-info">'+@message_count.to_s+'</span>'), messages_received_path  %></li>
<% else %>
 <li><%= link_to sanitize('<i class="icon-envelope"></i> ') + "Received", messages_received_path  %></li>
<% end %>

뷰 / 메시지 / refresh_part.js.erb

$('#message_received_count').html("#{escape_javascript(render 'layouts/messages_received_count', data: @message_count)}");

해결법

  1. ==============================

    1.당신은 아약스 요청을 전송하여 setInterval을 사용합니다 :

    당신은 아약스 요청을 전송하여 setInterval을 사용합니다 :

    $(document).ready(function () {
        // will call refreshPartial every 3 seconds
        setInterval(refreshPartial, 3000)
    
    });
    
    // calls action refreshing the partial
    function refreshPartial() {
      $.ajax({
        url: "whatever_controller/refresh_part"
     })
    }
    

    그럼 당신은이 같은 컨트롤러에서 작업을합니다

    def refresh_part
      # get whatever data you need to a variable named @data
      respond_to do |format|
        format.js
      end
    end
    

    당신은 (대신 HAML의 ERB 수)는 JS 파일 이름 refresh_part.js.haml을 작성합니다.

    refresh_part.js.haml는 다음과 같이 보일 것이다 :

    $('#part_you_want_to_refresh').html("#{escape_javascript(render 'name_of_partial', data: @data)}");
    

    당신이 routes.rb에서 올바른 경로를 설정합니다.

  2. ==============================

    2.참고로, refresh_part.js.erb는 다음과 같이 보일 것이다 :

    참고로, refresh_part.js.erb는 다음과 같이 보일 것이다 :

    $("#part").html("<%= escape_javascript(render 'partial', data: @data) %>");
    

    대신에:

    $('#part').html("#{escape_javascript(render 'partial', data: @data)}");
    

    또한, 우리는이를 단순화하기 위해 "escape_javascript"의 별칭을 사용할 수 있습니다 :

    $("#part").html("<%= j(render 'partial', data: @data) %>");
    
  3. ==============================

    3.그래 넌 할수있어

    그래 넌 할수있어

    <html>
    <head>
    <script type="text/JavaScript">
    <!--
    function timedRefresh(timeoutPeriod) {
        setTimeout("location.reload(true);",timeoutPeriod);
    }
    //   -->
    </script>
    </head>
    <body onload="JavaScript:timedRefresh(5000);">
    <p>This page will refresh every 5 seconds. This is because we're using the 'onload' event to call our function. We are passing in the value '5000', which equals 5 seconds.</p>
    <p>But hey, try not to annoy your users too much with unnecessary page refreshes every few seconds!</p>
    </body>
    </html>
    

    출처 : http://www.quackit.com/javascript/javascript_refresh_page.cfm

  4. from https://stackoverflow.com/questions/13988556/is-it-possible-to-refresh-partial-frequently-using-ajax by cc-by-sa and MIT license