Et lille eksempel:
I forhold til Michael bruger jeg setTimeout inde i funktionen selv. Dette for at undgå at du foretager et ajax kald før det foregående returnerer.
Javascript/HTML, to_message funktionen er ikke vigtig for updatering:
<html>
<head>
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
<script type="text/javascript">
function to_message(o){
var m ="";
if(o.source_profession == 'president'){
m += "The ";
}else{
if(o.source_nation.match(/^(a|e|y|u|i|o)/)){
m +="An ";
}else{
m +="A ";
}
}
m += o.source_nation +" " + o.source_profession + " " + o.action + " ";
if(o.target_profession == 'president'){
m += "the ";
}else{
if(o.target_nation[0].match(/^(a|e|y|u|i|o)/)){
m +="an ";
}else{
m +="a ";
}
}
m += o.target_nation + " " + o.target_profession;
return m;
}
function update(){
$.ajax({
url:'get_events.php',
success:function(data){
for(var i in data){
$('<div>'+to_message(data[i])+'</div>').prependTo("#events");
}
setTimeout(update, 100);
}
})
}
$(document).ready(function(){
setTimeout(update, 1000);
});
</script>
</head>
<body>
<div id="events">
</div>
</body>
</html>
Heller ikke så vigtigt da du formentlig har dine events andet sted:
<?php
header('Content-type: application/json');
class Event{
public $source_nation;
public $source_profession;
public $target_nation;
public $target_profession;
public $action;
}
$nations = array('amarican', 'russian', 'israeli', 'italian');
$professions = array('cook', 'president', 'gravedigger');
$actions = array('sat on', 'bombed', 'sainted');
$messages = array();
for($i = 0; $i < rand(0, 10); $i++){
shuffle($nations);
shuffle($professions);
shuffle($actions);
$event = new Event();
$event->source_nation = $nations[0];
$event->source_profession = $professions[0];
$event->target_profession = $professions[1];
$event->target_nation = $nations[1];
$event->action = $actions[0];
$messages[] = $event;
}
echo json_encode($messages);
?>