程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> PHP+ajax 無刷新刪除數據

PHP+ajax 無刷新刪除數據

編輯:PHP綜合
首先本例基於留言本整理版修改。
我們使用了jquery.js來實現ajax和dom刪除
首先加入
復制代碼 代碼如下:
<script type="text/javascript" src="lib/jquery.js"></script>

給table加個
復制代碼 代碼如下:
id="t<!--{$item.id}-->"

寫個js:
復制代碼 代碼如下:
<script>
function delItem (id) {
$.get('delete.php?id='+id,null,function (msg) {//ajax請求,請求後執行下面代碼
if ('1'==msg) {//返回1表示成功
$('#t'+id).remove();//把id為txx 的表格刪除
} else {//否則彈出錯誤信息
alert(msg);
}
});
}
</script>

刪除鏈接改成 href="javascript:delItem('<!--{$item.id}-->')"
delete.php的修改就是把錯誤語句改成直接輸出就行了。
OK完成。
index.tpl :
復制代碼 代碼如下:
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>所有留言</title>
<link rel="stylesheet" type="text/css" href="style.css" media="all" />
<script type="text/javascript" src="lib/jquery.js"></script>
</head>
<body>
<!--{if $smarty.session.username}-->
Welcome:<!--{$smarty.session.username}-->
<a href="logout.php">退出</a>
<!--{else}-->
<a href="login.php">登錄</a>
<a href="reg.php">注冊</a>
<!--{/if}-->
<a href="add.php">發表留言</a>
<!--{foreach from=$gblist item=item}-->
<table id="t<!--{$item.id}-->" width="700" border="0" cellspacing="0" cellpadding="0" class="tb">
<tr>
<td class="bg"><b>[<!--{$item.username}-->]</b> 發表於:<!--{$item.insert_time}--></td>
</tr>
<tr>
<td><!--{$item.content}-->
<br />
<!--{if $item.user_file}-->
附件:<a target="_blank" href="uploads/<!--{$item.user_file}-->"><!--{$item.user_file}--></a>
<!--{/if}-->
</td>
</tr>
<tr>
<td align="right"><!--{if $item.user_id==$smarty.session.user_id}--><a href="add.php?id=<!--{$item.id}-->">修改</a> <a href="javascript:delItem('<!--{$item.id}-->')">刪除</a><!--{/if}--></td>
</tr>
</table>
<!--{/foreach}-->
<!--{$pagePanel}-->
<script>
function delItem (id) {
$.get('delete.php?id='+id,null,function (msg) {
if ('1'==msg) {
$('#t'+id).remove();
} else {
alert(msg);
}
});
}
</script>
</body>
</html>

delete.php :
復制代碼 代碼如下:
<?php
require('common.php');
// 查詢出留言信息
$q = $query->query('select * from gb_content where id='.intval($_GET['id']));
$rs = $query->fetch_array($q);
$error = array();
if ($rs['user_id']!=intval($_SESSION['user_id'])) {// 判斷user_id是否相同
$error = '該信息你不能刪除,只能刪除自己發布的';
}
if (!$error) {
$query->query('delete from gb_content where id='.intval($_GET['id']));//刪除語句
if ($rs['user_file']) {//刪除附件
@unlink('uploads/'.$rs['user_file']);
}
echo 1;//表示成功
} else {
echo $error;
}
?>
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved