温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

ajax结合mysql数据库和smarty如何刷新局部数据状态

发布时间:2021-07-08 08:58:59 来源:亿速云 阅读:109 作者:小新 栏目:web开发

小编给大家分享一下ajax结合mysql数据库和smarty如何刷新局部数据状态,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

效果状态:通过点击锁定状态实现状态锁定与不锁定之间的切换

ajax结合mysql数据库和smarty如何刷新局部数据状态

1.主程序:01.php导入smarty和mysql类,取得数据导入列表模板

<?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.列表模板采用smarty遍历模板数据并显示,其中调用ajax改变锁定状态

<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8>
  <title>用户权限展示表</title>
</head>
<body>
    <table align="center" border="1" width="500">
      <center><h3>用户权限表</h3></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 './include/Mysql.class.php';
  $lock=$_GET['is_lock'];
  $uid=$_GET['uid'];
  $db=new Mysql;
  $result=$db->update('users',"is_lock=$lock","uid=$uid");
  if($result){
    echo true;
  }else{
    echo false;
  }
?>

看完了这篇文章,相信你对“ajax结合mysql数据库和smarty如何刷新局部数据状态”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI