0
我不知道这是否是正确的方法,但我想要完全按照标题的说法进行操作。我错过了一些jQuery概念,因为我是新手。通过jQuery从返回的JSON对象呈现ruby对象
我使用jQuery.rest:https://github.com/lyconic/jquery.rest
这个脚本定期检查,看是否在线和离线用户已更新:
<!-- Online checker -->
<script type="text/javascript">
$(function(){
setInterval (checkTrackings, 5000);
var js = '<checkTrackings> ';
function checkTrackings(){
$.read(
'/users/{id}/check',
{ id: <%= @user.id.to_json %> },
function (response) {
$("ul#online").empty();
$("ul#offline").empty();
// Code to add users back to list
$("ul#online").html('<%= escape_javascript(render(@online_users)).html_safe %>')
$("ul#offline").html('<%= escape_javascript(render(@offline_users)).html_safe %>')
console.log(js + 'Check trackings');
}
);
}
});
</script>
然而,不是@online_users和@offline_users,我需要返回的JSON对象,并需要将它们转换为所述变量。该脚本所调用的方法如下:
# Updates contacts
def check
@online_users = Array.new
@offline_users = Array.new
@user = User.find(params[:id])
@followed_users = @user.followed_users
@followed_users.each do |followed_user|
@online_users.push(followed_user) if followed_user.state.online
end
@offline_users = @followed_users - @online_users
respond_to do |format|
format.js { render :json => { :online_users => @online_users, :offline_users => @offline_users } }
end
end
其他任何提示都会很好。我对web dev非常陌生。谢谢您的帮助!
真棒,这是在测试我只是做了。当没有用户在线时,'response.online_users'为空,当1个用户在线时变为[object Object]。所以我得到了json,但是我如何将它们转换回ruby?谢谢。 –
你是否想将它转换回可以传回给操作的东西?让他们从前端转换回红宝石的应用程序有什么用? – chaseadamsio
我已经有一种方法来呈现红宝石对象。所以我想用这个代码:$(“ul#online”)。html('<%= escape_javascript(render(@online_users))。html_safe%>'),其中@online_users从response.online_users更新。这是朋友列表及其在线状态的定期更新。 –