How can I make a database driven list/feed that can be updated with jQuery ajax?
I'm wanting to know what the best way to go about creating a list of say, users's statuses (similar to what facebook/twitter has) that is loaded in with PHP when the page loads. But ajax checks for new status updates every 10 seconds or so.
It looks like to me that there are about 2 options: Put the "new items" html in the PHP file that gets called by ajax, and append it to the element containing the status feed. (this also defeats the purpose of JSON)
or
use something like jTemplates. but as far as i can see this option would not be ideal because when the page first loads it has to do an ajax post/get request.
How does everyone else do theirs? I want to do开发者_开发技巧 things the best, most 'pro' way!
I'd use something like this:
$(function() {
var updateStatus = function() {
var options = {
url: "some/address/that/returns/JSON",
dataType: "json",
success: function(data, textStatus) {
// use JSON to update you're markup...
setTimeout(updateStatus, 10);
}
};
$.ajax(options);
};
setTimeout(updateStatus, 10);
});
It seems as though you're crossing a responsibility boundary. Do you want PHP to be responsible for rendering the HTML? Or do you want javascript/json to be responsible?
Since you want to dynamically update the list, I would use a javascript library like jQuery to perform the ajax request and to handle the json response, and then add new items to the list. There are tutorials for this all over the web.
This will also help keep your sanity in check because when you have to debug (and you WILL have to debug), you only need to work on one set of code using one paradigm: the javascript/json approach, rather than switch mentally between the PHP/HTML and javascript/json side.
Just my $0.02
Use APE the Ajax Push Engine, it's written especially for this job. Checkout this Twitter demo to see it in action.
Ill say you could load the contents into a DIV upon page load.
It doesn't matter if you populate using PHP or javascript to do this on page load.
Then using some sort of javascript sleep script, automatically, every XX amount of seconds reload the DIV html via jQuery with the contents of a PHP page which grabs info about user statuses. Put the function to load the user statuses on an endless loop with the Sleep function pausing before the updates.
http://www.geekpedia.com/KB55_How-do-I-make-a-JavaScript-function-wait-before-executing-%28sleep-or-delay%29.html
I'm guessing the jquery pseudo code would go.
$.get("user_statuses.php", function(data){
$("div").html(data); // replace the data in the div with user_statuses.php
sleep(15 seconds); // sleep until next
});
Make it a recursive call I'm guessing. Don't know if the javascript will crap out eventually but this is an idea.
精彩评论