Ajax不会每3秒重新加载一次。为什么?

时间:2012-12-21 14:21:25

标签: ruby-on-rails ruby-on-rails-3 jquery

我正在尝试让它重新加载显示每3秒未读取的消息数量的部分。

但是我写的代码根本没有显示数字,即使有1条未读信息......
如何重新加载显示正确数量的未读消息的部分?

我的代码是

资产/ 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)}");

1 个答案:

答案 0 :(得分: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部分 - rails知道如何自动执行此操作。)

修改

经过讨论 - 要解决的最后一个问题与JQuery冲突有关 - JQuery被包含在多个地方并且停止$(文件).ready被解雇。固定的。