【发布时间】:2018-07-29 06:01:39
【问题描述】:
我的英语不好。对不起。我相信你明白我的意思。 我在下面分享的代码质疑是否有新内容,如果有,请将新内容添加到页面中。但我不知道更新或删除相同或不同(id)需要什么逻辑。如何进行更新和删除?
index.php
<?php require "ayar.php"; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>jQuery Ajax ile Anlık Veri Güncelleme Uygulaması</title>
<style type="text/css">
ul, li {padding: 0; margin: 0; list-style: none; font: 14px Arial}
ul li {padding: 5px; background: #eee; margin-bottom: 5px}
ul li.new {background: lightgreen}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
<ul>
<?php
$query = mysql_query("SELECT * FROM veri ORDER BY veri_id DESC");
while ($row = mysql_fetch_object($query)){
echo '<li id="'.$row->veri_id.'">'.$row->veri_text.'</li>';
}
?>
</ul>
<div id="sonuc"></div>
</body>
</html>
ajax.php
<?php
require "ayar.php";
if ($_POST){
$lastid = $_POST["lastid"];
if (!$lastid){
$array["hata"] = "Geçersiz işlem!";
} else {
$query = mysql_query("SELECT * FROM veri WHERE veri_id > $lastid ORDER BY veri_id DESC");
if (mysql_affected_rows()){
while ($row = mysql_fetch_object($query)){
$array["veriler"] = '<li class="new" id="'.$row->veri_id.'">'.$row->veri_text.'</li>';
}
}
}
echo json_encode($array);
}
?>
ajax.js
$(function () {
$ajaxLoad = function () {
var lastid = $("ul li:first").attr("id");
$.ajax({
type: "post",
url: "ajax.php",
data: {"lastid": lastid},
dataType: "json",
success: function (result) {
if (result.error) {
$("#result").html(result);
}
else{
$("ul").prepend(result.data);
}
}
});
}
setInterval("ajaxLoad()",5000);
【问题讨论】:
-
请注意
mysql_的构造函数是deprecated as of PHP 5.5,是removed in PHP 7。请考虑切换到MySQLi 或PDO,确保您也使用prepared statements 来防止SQL injection :)