Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

php - Reload AJAX data every X minutes/seconds, jQuery

I programmed a CMS that has a log of who has recently logged into the system. Presently, this data is fed into a jQuery UI tab via Ajax. I would like to put this information into a sidebar on the main page and load it via AJAX every 30 seconds (or some set period of time).

How would I go about doing this? Does the PHP response need to be JSON coded? I am fairly new to AJAX and JSON data.

Here is the PHP I am currently using to pull details from the users table-

<?php
$loginLog = $db->query("SELECT name_f, name_l, DATE_FORMAT(lastLogin, '%a, %b %D, %Y %h:%i %p') AS lastLogin FROM user_control ORDER BY lastLogin ASC LIMIT 10");
while ($recentLogin = $loginLog->fetch()) {
echo $recentLogin['name_f'] . " " . $recentLogin['name_l'] . " - " . $recentLogin['lastLogin'];
}
?>

Thanks! UPDATE

Okay, this is what I have so far.. the part I'm stuck on is how to loop through JSON and enter it into the box. It works fine as long as I use just one result and assure it is not in [ ]'s. I'm just learning Ajax and JSON, for some reason it isn't coming to me too easily.

Javascript -

$(document).ready(function(){

                function refreshUsers(){

                    $.getJSON('json.php', function(data) {

                            for (var i = 0; i < data.length; i++) {

                                $("#loadHere").html('<p>' + data.name + ' ' + data.lastLogin + '</p>');

                            }

                });

            }

                var refreshInterval = setInterval(refreshUsers, 30 * 1000);

                refreshUsers();

            });

What my PHP script outputs -

[{"name":"Joe Smith","lastLogin":"Fri, May 21st, 2010 08:07 AM"},{"name":"Jane Doe","lastLogin":"Fri, May 21st, 2010 07:07 AM"}]

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

PHP side, use json_encode().

Client side, use $.getJSON():

function refreshUsers(){
  $.getJSON(url, postData, function (data, textStatus){
    // Do something with the data
  });
}

// Keep interval in a variable in case you want to cancel it later.
var refreshInterval = setInterval(refreshUsers, 30 * 1000);

With these 2, you should have a lot to get started with. More than this, you'd be asking us to work for you :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...