I don't know if this is the right approach, but I want to do exactly what the title says. I'm missing some jQuery concepts, as I'm new to it.
I am using jQuery.rest: https://github.com/lyconic/jquery.rest
This script periodically checks to see if the online and offline users have been updated:
<!-- 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>
However, instead of @online_users and @offline_users, I need the returned JSON objects and need to convert them to said variables. The method that this script calls is here:
# 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
Any other tips would be nice, too. I'm very new to web dev. Thanks for the help!
have you tried logging the response in
function (response) {...}
your response should have response.online_users and response.offline_users objects respectively, so log as:
function (response) {
console.log(response.online_users, response.offline_users);
...
}
and see if your response contains your json objects?
So if you have response.online_users, you'll want to do this in your javascript:
// Code to add users back to list
var online_users = response.online_users,
online_users_len = online_users.length,
buffer = [];
for(var i = 0; i < online_users_len; i++) {
buffer.push("<li>", online_users[i], "</li>");
}
$("ul#online").html(buffer.join(""));
// Put the offline user count in ul#offline
$("ul#offline").html(response.offline_users);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.