English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Exemplo de mudança de estado e exclusão sem recarregar usando ajax

1. 01.php como programa principal, chamando o template smarty para percorrer e exibir:

<?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 template: conteúdo combinado com JS ajax:

<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8>
  <title>Exibição de Tabela de Permissões de Usuário</title>/title>
</head>
<body>
    //Definir um div para o corpo do table, facilitando a chamada do js
    <div id="table">
    <table align="center" border="1" width="500">
      <center><h2>Tabela de Permissões de Usuário</th>/h2></center>
      <tr>
        <th>uid</th>/th><th>Nome de Usuário</th>/th><th>Senha</th>/th><th>Estado de Bloqueio</th>/th><th>Rol</th>/th><th>Operação</th>/th>
      </tr>  
      {foreach $lists as $list}
        <tr align="center">
          <td>{$list.uid}</td>/td>
          <td>{$list.username}</td>/td>
          <td>{$list.password}</td>/td>
          {if $list.is_lock==1}
            <td><a href="javascript:lock(0,{$list.uid});" rel="external nofollow">Bloquear</a>/a></td>
            {else}
            <td><a href="javascript:lock(1,{$list.uid})" rel="external nofollow" ;>Unlock</a></td>  
          {/if}    
          {if $list.role==1}
              <td>Administrator</td>
          {else}
              <td>Editor</td>    
          {/if}
          <td><a href="javascript:del({$list.uid})" rel="external nofollow" >Delete</a></td>
        </tr>    
      {/foreach}  
    </table>
    </div>  
</body>
    <script type="text/javascript">
      function lock(lock,uid){
          //Create AJAX object
          var xhr=new XMLHttpRequest();
          //Open a link
          xhr.open('post','02.php');
          //Set header information
          xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
          //Value, multiple parameters separated by &
          var data="is_lock="+lock+"&uid="+uid;
          //Send AJAX data request
          xhr.send(data);
          //Set callback, listen function
          xhr.onreadystatechange=function(){
            //If the AJAX status code response is normal and the network is normal, get the response text
            if(xhr.readyState==4&&xhr.status==200){
              if(xhr.responseText){
                document.getElementById('table').innerHTML=xhr.responseText;
              }else{
                alert("Failed to switch status!");
              }
            }
          }
        }
    function del(uid){
      var del=window.confirm("Are you sure you want to delete? ");
      if(del){
        //Create AJAX object
        var xhr=new XMLHttpRequest();
        //Open a link
        xhr.open('post','del.php');
        //Set header
        xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
        //data value
        var data="uid="+uid;
        //Send AJAX request
        xhr.send(data);
        //Set listener
        xhr.onreadystatechange=function(){
          //If the AJAX status code response is normal and the network is normal, get the response text
          if(xhr.readyState==4&&xhr.status==200){
            if(xhr.responseText){
              //Use AJAX response content to replace the content of the table tag in this template
              document.getElementById('table').innerHTML=xhr.responseText;
            }else{
              alert("Falha na exclusão!");
            }
          }
        }
      }
    }    
    </script>
</html>

3. 02.php alterar o estado sem recarregar:

<?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){
    //A atualização foi bem-sucedida. Recorra ao banco de dados e exiba o modelo Smarty novamente
    $lists=$db->getALL('users');
    $smarty->assign('lists',$lists);
    $smarty->display('list.html');
  }else{
    echo false;
  }
?>

4.del.php para excluir sem recarregar

<?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;
  }
?>

Este exemplo de implementação de AJAX para alterar o estado e excluir sem recarregar, compartilhado pelo editor, é tudo o que temos a oferecer. Esperamos que isso forneça uma referência útil e esperamos que você apoie e incentive o tutorial Yell.

Declaração: O conteúdo deste artigo é de origem na internet, pertencente ao respectivo proprietário. O conteúdo é contribuído e carregado voluntariamente pelos usuários da internet. Este site não possui direitos autorais, não foi editado artificialmente e não assume responsabilidades legais relacionadas. Se você encontrar conteúdo suspeito de violação de direitos autorais, por favor, envie um e-mail para: notice#oldtoolbag.com (ao enviar e-mail, substitua # por @ para denunciar e forneça provas relevantes. Aos verificarmos, o site deletará imediatamente o conteúdo suspeito de violação de direitos autorais.)

Você também pode gostar