Mysql
 SQL >> Datenbank >  >> RDS >> Mysql

Live-Updates für <li>-Elemente mit jQuery und PHP realisieren

Ein Plugin ist dafür nicht nötig. Mit jQuery und wiederkehrenden AJAX-Aufrufen lässt sich das selbst umsetzen. Nutzen Sie setInterval() für die periodischen Requests und .prepend(), um neue Einträge einzufügen.

HTML

<html>
<head>
<title>Tweets</title>
<script type="text/javascript"
  src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>
#tweets { width: 500px; font-family: Helvetica, Arial, sans-serif; }
#tweets li { background-color: #E5EECC; margin: 2px; list-style-type: none; }
.author { font-weight: bold }
.date { font-size: 10px; }
</style>
<script>
jQuery(document).ready(function () {
    setInterval(showNewTweets, 1000);
});

function showNewTweets() {
    $.getJSON("feed.php", null, function (data) {
        if (data != null) {
            $("#tweets").prepend(
                $("<li><span class=\"author\">" + data.author + "</span> "
                  + data.tweet + "<br /><span class=\"date\">"
                  + data.date + "</span></li>").fadeIn("slow")
            );
        }
    });
}
</script>
</head>
<body>
<ul id="tweets"></ul>
</body>
</html>

PHP

<?php
echo json_encode(array(
    "author" => "someone",
    "tweet"  => "Die Uhrzeit ist: " . time(),
    "date"   => date('l jS \of F Y h:i:s A')
));
?>

Sicherheitshinweis: Setzen Sie die Werte mit .text() statt String-Konkatenation ein, sonst entsteht eine XSS-Lücke. Ein Intervall von einer Sekunde erzeugt zudem unnötige Last – 10 bis 30 Sekunden sind in der Praxis meist ausreichend.