首頁  >  文章  >  web前端  >  ajax結合mysql資料庫實現局部資料刷新

ajax結合mysql資料庫實現局部資料刷新

php中世界最好的语言
php中世界最好的语言原創
2018-03-30 15:41:242322瀏覽

這次帶給大家ajax結合mysql資料庫實作局部資料刷新,ajax結合mysql資料庫實作局部資料刷新的注意事項有哪些,下面就是實戰案例,一起來看一下。

效果狀態:透過點選鎖定狀態實現狀態鎖定與不鎖定之間的切換

#1.主程式:01.php導入smarty和mysql類,取得資料導入列表模板

<?php
  include &#39;./include/Mysql.class.php&#39;;
  include &#39;./libs/Smarty.class.php&#39;;
  $db=new Mysql;
  $smarty=new Smarty;
  $lists=$db->getALL('users');
  $smarty->assign('lists',$lists);
  $smarty->display('list.html');
?>

2.列表模板採用smarty遍歷範本資料並顯示,其中呼叫ajax改變鎖定狀態

<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8>
  <title>用户权限展示表</title>
</head>
<body>
    <table align="center" border="1" width="500">
      <center><h2>用户权限表</h2></center>
      <tr>
        <th>uid</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}
        </tr>    
      {/foreach}  
    </table>  
</body>
    <script type="text/javascript">
      function lock(lock,uid){
          //创建ajax对象
          var xhr=new XMLHttpRequest();
          //打开一个链接
          xhr.open('get','02.php?is_lock='+lock+"&uid="+uid);
          //发送ajax请求
          xhr.send(null);
          //设置回调、监听函数
          xhr.onreadystatechange=function(){
            //如果ajax状态码响应正常且网络正常,获取响应文本
            if(xhr.readyState==4&&xhr.status==200){
              if(xhr.responseText){
                window.location.reload();
              }else{
                alert("切换状态失败!");
              }
            }
          }
        }
    </script>
</html>

#3.ajax回應腳本,接收ajax透過get方式傳遞過來的資料變更資料庫內容並回應文字傳回js腳本

<?php
  include &#39;./include/Mysql.class.php&#39;;
  $lock=$_GET[&#39;is_lock&#39;];
  $uid=$_GET[&#39;uid&#39;];
  $db=new Mysql;
  $result=$db->update('users',"is_lock=$lock","uid=$uid");
  if($result){
    echo true;
  }else{
    echo false;
  }
?>

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

ajax實作動態餅圖與長條圖的圖文詳解

判斷是否為整數,小數或實數正規有哪些寫法

以上是ajax結合mysql資料庫實現局部資料刷新的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn