1. 01.php為主程序,調用smarty模板遍歷輸出:
?php
include './include/Mysql.class.php';
include './libs/Smarty.class.php';
$db=new Mysql;
$smarty=new Smarty;
$lists=$db->getALL('users');
$smarty->assign('lists',$lists);
$smarty->display('list.html');
?>
2. list.html模板:內容結合JS ajax使用:
!DOCTYPE html>
html>
head>
meta charset=utf-8>
title>用戶權限展示表/title>
/head>
body>
//給table體設置一個div,方便js調用
div id="table">
table align="center" border="1" width="500">
center>h2>用戶權限表/h2>/center>
tr>
th>uid/th>th>用戶名/th>th>密碼/th>th>鎖定狀態/th>th>角色/th>th>操作/th>
/tr>
{foreach $lists as $list}
tr align="center">
td>{$list.uid}/td>
td>{$list.username}/td>
td>{$list.password}/td>
{if $list.is_lock==1}
td>a href="javascript:lock(0,{$list.uid});" rel="external nofollow" >鎖定/a>/td>
{else}
td>a href="javascript:lock(1,{$list.uid})" rel="external nofollow" ;>取消鎖定/a>/td>
{/if}
{if $list.role==1}
td>管理員/td>
{else}
td>編輯者/td>
{/if}
td>a href="javascript:del({$list.uid})" rel="external nofollow" >刪除/a>/td>
/tr>
{/foreach}
/table>
/div>
/body>
script type="text/javascript">
function lock(lock,uid){
//創建ajax對象
var xhr=new XMLHttpRequest();
//打開一個鏈接
xhr.open('post','02.php');
//設置頭信息
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
//取值,多個參數用分開
var data="is_lock="+lock+"uid="+uid;
//發送ajax數據請求
xhr.send(data);
//設置回調、監聽函數
xhr.onreadystatechange=function(){
//如果ajax狀態碼響應正常且網絡正常,獲取響應文本
if(xhr.readyState==4xhr.status==200){
if(xhr.responseText){
document.getElementById('table').innerHTML=xhr.responseText;
}else{
alert("切換狀態失敗!");
}
}
}
}
function del(uid){
var del=window.confirm("您確定要刪除嗎?");
if(del){
//創建ajax對象
var xhr=new XMLHttpRequest();
//打開一個鏈接
xhr.open('post','del.php');
//設置header頭
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
//data取值
var data="uid="+uid;
//發送ajax請求
xhr.send(data);
//設置監聽
xhr.onreadystatechange=function(){
//如果ajax狀態碼響應正常且網絡正常,獲取響應文本
if(xhr.readyState==4xhr.status==200){
if(xhr.responseText){
//用ajax響應內容替換本模板中table標簽的內容
document.getElementById('table').innerHTML=xhr.responseText;
}else{
alert("刪除失敗!");
}
}
}
}
}
/script>
/html>
3. 02.php改變狀態無刷新:
?php
include './include/Mysql.class.php';
include './libs/Smarty.class.php';
$lock=$_POST['is_lock'];
$uid=$_POST['uid'];
$smarty=new Smarty;
$db=new Mysql;
$result=$db->update('users',"is_lock=$lock","uid=$uid");
if($result){
//修改成功重新遍歷數據庫并輸出smarty模板
$lists=$db->getALL('users');
$smarty->assign('lists',$lists);
$smarty->display('list.html');
}else{
echo false;
}
?>
4.del.php實現刪除無刷新
?php
include './include/Mysql.class.php';
include './libs/Smarty.class.php';
$db=new Mysql;
$smarty=new Smarty;
$uid=$_POST['uid'];
$res=$db->delete('users',$uid);
if($res>0){
$lists=$db->getALL('users');
$smarty->assign('lists',$lists);
$smarty->display('list.html');
}else{
echo false;
}
?>
以上這篇ajax實現改變狀態和刪除無刷新的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:- jquery ajax 局部無刷新更新數據的實現案例
- 淺談Ajax技術實現頁面無刷新
- PHP+ajax 無刷新刪除數據
- ajax實現頁面加載和內容刪除