【问题标题】:How can I use JSON and Perl (HTML::Mason) to create dynamic web page with AJAX?如何使用 JSON 和 Perl (HTML::Mason) 通过 AJAX 创建动态网页?
【发布时间】:2010-12-13 19:24:31
【问题描述】:

我对处理 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;
   }

以及 Mason 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>

【问题讨论】:

    标签: ajax perl json mason


    【解决方案1】:

    很抱歉让你们浪费了时间。我终于解决了我的问题:

    在我的 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>
    

    【讨论】:

    • 也许您可以总结一下大代码转储,以便我们通过阅读几句话就知道您做了什么:)
    • 嗨,brian d foy,是的,我可以,但是我看到了一个问题,当有人来看代码时,它不会看到有效的代码。我讨厌有些事情不完整。我同意的是将我的葡萄牙语 cmets 更改为英语。
    • tl;tr 摘要:使用print qq{ { id : $rid } }; 以 JSON 格式向客户端返回 id。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    相关资源
    最近更新 更多