0

3秒ごとに未読メッセージの数を示すパーシャルをリロードさせようとしています。

しかし、未読メッセージが1つある場合でも、私が書いたコードには数字がまったく表示されません...未読メッセージの
正しい数を示すパーシャルをリロードするにはどうすればよいですか??

私のコードは

assets/javascript/refresh_messages_count.js

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

function refreshParital() {
  $.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>

ビュー/メッセージ/refresh_part.js.erb

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

1 に答える 1

1

関数 refreshPartial を次のように変更します。

function refreshPartial() {
  $.ajax({
    url: "/messages/refresh_part",
    type: "GET",
    dataType: "script",
    success: function(data) {
             console.log("Called refresh_part");
    },
    error: function (xhr, ajaxOptions, thrownError) {
      alert("Error: " + xhr.status + " " + thrownError);
    }
  });
}

(/メッセージの前は重要です。他のフィールドも同様に役立ちます。成功オプションは、機能するようになったら削除できます)。

コントローラーのメソッドを次のように変更します。

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 
    end
end

(パーツの削除render- レールはこれを自動的に行う方法を知っています)。

編集

議論の後、解決すべき最後の問題は JQuery の競合に関連していました。JQuery は複数の場所に含まれており、$(document).ready の起動を停止していました。修理済み。

于 2012-12-21T15:31:22.220 に答える