簡體   English   中英

如何使用 JSON 和 Perl (HTML::Mason) 使用 AJAX 創建動態網頁?

[英]How can I use JSON and Perl (HTML::Mason) to create dynamic web page with AJAX?

我對處理 Javascript、JSON 和 Perl 的方式有些迷茫,而且大多數示例都在 PHP 中,這對我沒有幫助。

我有一個頁面(稱為 main.html),其中包含來自 MySQL 的數據,並且可以選擇按 id 刪除一行。

然后我讓 Javascript 將 id 發送到頁面 apagar.html 這現在有點混亂因為我試圖處理 JSON,但是使用 GET 它可以工作,並且缺少的是刪除請求后的刷新。 但我想在我的代碼中引入 JSON 並使頁面更加動態,但不知道如何。

在我的 apagar.html 中,如果 url 中有任何 id,我只有要刪除的代碼。

我已經閱讀了 IBM 系列(掌握 Ajax): http : //www.ibm.com/developerworks/web/library/wa-ajaxintro11.html? S_TACT=105AGX08&S_CMP=EDU

感謝您的幫助,上面是我正在使用的 javascript:

<script language="javascript" type="text/javascript">
  var pedido = false; // pedido = request

  try {
     pedido = new XMLHttpRequest();
  }
    catch (failed) {
       pedido = false
    }

  if (!pedido) {
     alert("O seu browser não é suportado."); // Browser not supported
  }

   function Eliminar(rid) { // relativo a main.html & apagar.html
      //alert("SK"); //debug
      if ( confirm("Deseja realmente eliminar?") ) {
       var url = "/back/apagar.html?rid=" + escape(rid);
       /*POST*/
       pedido.open("POST", url, true);
       pedido.onreadystatechange = updatePage;
       pedido.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

       pedido.send( contacto.toJSONString() );
       //pedido.open("GET", url, true);
       //pedido.send(null);

      }
      return false;
   }

和梅森 apagar.html 頁面

<%args>
$rid => ''
</%args>

<%once>
use lib '/var/www/projectox/';
use db::Conexao; #interacao com a DB
use DBI;
use Apache2::Cookie; #interacao com cookies
</%once>

<%init>
% # vê se existem cookies
my $cookies = Apache2::Cookie->fetch($r);
 if(!$cookies){ #sem cookies é enviado para o login
  $m->redirect('login.html');
 }

 if($rid) {
  # vai eliminar os dados pelo valor do id ($rid)

  #ligacao à DB
  my $tomada = db::Conexao->Conexao();

  my $sql = $tomada->prepare("Delete from Contactos where id=?") ||
    die "Impossivel de realizar a operação: $!";

 $sql->execute($rid) || die "Não foi possivel executar: $!";

 #desliga da DB
 $tomada->disconnect || warn "Não foi possivel terminar a ligação!";

</%init>

抱歉讓你們耽誤了時間。 我終於解決了我的問題:

在我的 Javascript(使用 JQuery)中,我已經完成了:

$(document).ready(function() {
  // relativo ao main.html
  $("#over_tabela tr").mouseover(function() {
    $(this).addClass("sobre_linha");
  }).mouseout(function() {
    $(this).removeClass("sobre_linha");
  });

  // this is to "delete" the row from the table of main.html file throw ajax and JSON
  $('a.delete_link').click(function(e) {
    e.preventDefault();
    if (confirm('Tem a certeza?')) {
      url = $(this).attr('href');
      $.ajax({
        type: "GET",
        url: url,
        dataType: "json",
        success: function(msg) {
          $('#linha_' + msg.id).hide("slow");
        }
      });
    }
  });
});

然后在我的 apagar.html 中:

<%args>
$rid => ''
</%args>

<%once>
use lib '/var/www/projectox/';
use db::Conexao;    # module that interact with database
use DBI;
use Apache2::Cookie;    #cookies, not the right way, gonna update to Session Cookies
</%once>

<%init>
# vê se existem cookies
my $cookies = Apache2::Cookie->fetch($r);
    if(!$cookies) { #sem cookies é enviado para o login
        $m->redirect('login.html');
    }

 if($rid) {
  # vai eliminar os dados pelo valor do id ($rid)

  #database connection
  my $tomada = db::Conexao->Conexao();

  my $sql = $tomada->prepare("Delete from Contactos where id=?") ||
     die "Impossivel de realizar a operação: $!";

    $sql->execute($rid) || die "Não foi possivel executar: $!"; # execute or die with a message

    #disconnect from database or warn about problem
    $tomada->disconnect || warn "Não foi possivel terminar a ligação!";

    print qq{ { id : $rid } }; #JSON style, this was what made me go crazy... lol and in the end was soooooo easy as that
  }
</%init>

最后在我的 main.html 中:

    <%args>
$sair => 0
</%args>

<%once>

use lib '/var/www/projectox/';
use db::Conexao;
use DBI;
use Apache2::Cookie;
</%once>

<%init>
# vê se existem cookies
my $cookies = Apache2::Cookie->fetch($r);
    if(!$cookies){ #without cookies user is redirect to login.html
     $m->redirect('login.html');
    }

    if($sair){ # if he logout : cookie expire and user is sent to index.html
    my $cookie = Apache2::Cookie->new($r,
        -name => "CHOCO",
        -value => "TWIX",
        -expires=> '+0s'
        );
        $cookie->bake($r);
     $m->redirect('../index.html');
    }


    my $tomada = db::Conexao->Conexao();    

    my $sql = $tomada->prepare("Select * from Contactos") ||        # select all from table Contactos or die..
        die "Impossivel : $!";

    $sql->execute() || die "Nao foi possivel executar: $!"; 

    # Generate HTML here
    print qq{
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="pt" xml:lang="pt">
<head>
    <meta http-equiv="Content-Type" content="text/html"; charset="utf-8" />
    <link rel="stylesheet" type="text/css" href="../shadowbox/shadowbox.css">
    <link rel="stylesheet" href="../css/estilo.css" type="text/css" />

    <script language="javascript" src="../js/jquery.js"></script>
    <script language="javascript" src="../js/wii.js"></script>

    <script type="text/javascript" src="../shadowbox/shadowbox.js"></script>

    <script type="text/javascript">
    Shadowbox.init({
        language:   "pt-PT",
        players:    ["html","iframe","qt"],
        viewportPadding: 30,
        overlayOpacity:  0.9,
        overlayColor: "#9999ff"
    });
    </script>
</head>
<body>
    <form id="logout" name="logout" action="" method="post" >
        <p>
            <input type="submit" id="sair" name="sair" value="Sair" />
        </p>
    </form>
    Bem Vindo #USERNAME !
    <table id="over_tabela" name="over_tabela" align="center" border="0" cellspacing="1" cellpadding="5">
    <thead>  
      <tr>
        <th>NOME</th><th>E-MAIL</th><th>MENSAGEM</th><th>OP&Ccedil;&Atilde;O</th>
      </tr>
    </thead>
        };

    my @dados; # receive data from database
    my $dados; # part of @dados, id -> $dados[0]; nome -> $dados[1] etc..

    while ( @dados = $sql->fetchrow_array() ) { #data is sent in html table form
        print qq{
        <tbody>
            <tr id="linha_$dados[0]">
                <td>$dados[1]</td><td>$dados[2]</td><td>$dados[3]</td>
                <td>
                    <a class="edit_link" href="/back/editar.html?rid=$dados[0]" rel="shadowbox;width=440;height=320">
                        <img src="../imagens/editar.png" width="24" height="24" border="0" title="Editar" />
                    </a>
                    &nbsp;
                    <a class="delete_link" href="/back/apagar.html?rid=$dados[0]">
                        <img src="../imagens/eliminar.png" width="24" height="24" border="0" title="Apagar" />
                    </a>
                </td>

            </tr>
        </tbody>
        };
    }
    print qq {</table>
</body>
</html>}; #end of HTML

    #disconnect from database
    $tomada->disconnect || warn "Não foi possivel terminar a ligação: $!";
</%init>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM