2013-07-26 34 views
0

提前感謝您的時間。如何張貼表格到動態加載的同一頁面

我有一個PHP網頁動態地填補取決於這樣的URL一個HTML部分:

<section id="sect_info"> 
    <?php 
     $existingPages = array('main', 'createacc'); 

     if (isset($_GET['p'])) { 
      $requestedPage = $_GET['p']; 

      if (in_array($requestedPage, $existingPages)) { 
       if (file_exists($requestedPage.'.php')) include_once($requestedPage.'.php'); 
       else echo "La pagina solicitada no existe."; 
      } 
      else include_once('main.php'); 
     } 
     else include_once('main.php'); 
     ?> 
</section> 

具有用於該部分內容的PHP如下:

<?php 

if (isset($_POST['user']) && isset($_POST['pwd'])) { 
    createAcc(); 
} 
else { 
    echo " 
    <table cellpadding='0' cellspacing='0' class='table_info'> 
     <tr> 
      <td class='topWnd' align='center'> Nueva cuenta 
      </td> 
     </tr> 
     <tr> 
      <td class='contenidoInfo'> 
       <form action='createacc.php' method='post'> 
        <table> 
         <tr> 
          <td>Usuario:</td> 
          <td><input type='text' maxlength='10' name='user'></td> 
         </tr> 
         <tr> 
          <td>Contraseña:</td> 
          <td><input type='password' maxlength='10' name='pwd'></td> 
         </tr> 
         <tr> 
          <td>Repetir contraseña:</td> 
          <td><input type='password' maxlength='10' name='repeatPwd'></td> 
         </tr> 
         <tr> 
          <td>E-mail:</td> 
          <td><input type='text' maxlength='60' name='email'></td> 
         </tr> 
         <tr> 
          <td>Pregunta secreta:</td> 
          <td><input type='text' maxlength='60' name='question'></td> 
         </tr> 
         <tr> 
          <td>Respuesta secreta:</td> 
          <td><input type='text' maxlength='60' name='answer'></td> 
         </tr> 
        </table> 
        <p><input type='checkbox' name='rules'> Estoy de acuerdo con las reglas de Helbreath OS.</p> 
        <p><input type='submit' value='Crear cuenta'></p> 
       </form> 
      </td> 
     </tr> 
    </table>"; 
} 

function createAcc() { 
    include_once("include/account.php"); 
    include_once("include/main.php"); 

    // -- Variables globales 
    $usuario = $_POST["user"]; 
    $contraseña = $_POST["pwd"]; 
    // -- 

    // Verificamos que los datos ingresados sean validos 
    if (!empty($usuario) and !empty($contraseña)) 
    { 
     // se verifica la longitud de los campos para no generar conflictos con la base de datos 
     if ((strlen($usuario) <= 10) && ((strlen($contraseña) >= 4) && (strlen($contraseña) <= 10))) { 
      // Luego de verificar la información establecemos la comunicacion con la base de datos. 

      $mainObj = new Main; // Instancia de Main 

      // Intentamos conectar a la base de datos y almacenamos el resultado 
      // de la conexion en una variable. 
      $conexResult = $mainObj->ConnectToDatabase(); 

      if ($conexResult != "") // La conexión no ha sido exitosa. Mostramos el resultado 
      { 
       echo $conexResult; 
       $mainObj->CloseCon(); 
       return; 
      } 

      $accObj = new Account; // Instancia de Account 

      // verificamos si la cuenta que se quiere crear ya existe 
      if ($accObj->CheckExistingAccount($mainObj->getConexObj(), $usuario)) 
      { 
       echo "La cuenta: ".$usuario." ya existe!."; 
       $mainObj->CloseCon(); 
       return; 
      } 
      else 
      { 
       if ($accObj->CreateNewAccount($mainObj->getConexObj(), $usuario, $contraseña))   
        echo "<p style='color:green;'>La cuenta: ".$usuario." fue creada exitosamente.!</p>"; 
       else 
        echo "<p style='color:red;'>La cuenta: ".$usuario." no ha podido crearse.!</p>"; 
      } 
     } 

     // Cerramos la conexion a la base de datos 
     $mainObj->CloseCon(); 
    } 
} 
?> 

問題是當用戶提交表單時,結果顯示在空白頁面上。我需要的是在php加載的同一節中顯示php動作的結果。

我試過使用jQuery和ajax,替換「輸入類型按鈕」的「輸入類型提交」,並處理jQuery的提交事件,但似乎jQuery無法找到表單元素。

因此:我如何發佈表單並將其結果顯示到我之前提到的那個部分?

對不起,我的英語不好。如果你需要更多的細節或更多的代碼或任何只是告訴我。

再次感謝!

+0

之外,你有沒有一些實際的jQuery代碼顯示? – putvande

+0

只是一個簡單的參考:echo並不是真正意義上的回聲,它實際上不是動態構建的預定義HTML的大塊。你可能要考慮在'

'之前關閉你的PHP'?>',然後在表'
'後面重新打開它。這樣您就不必擔心正確轉義引號或使用其他類型的引號。它也將允許您的編輯器提供正確的代碼突出顯示,因爲它不再只是一個大字符串。 – War10ck

+0

謝謝你的回覆和你的時間。好的提示War10ck謝謝你! –

回答

1

要做一個ajax職位,並更換表格容器的內容,你應該這樣做。

$('#sect_info form').on('submit', function(e){ 
    e.preventDefault(); 
    // do client side check of values 
    if ($(this).find("input[name=user]").val() == '' || 
     $(this).find("input[name=pwd]").val() == '' || 
     $(this).find("input[name=pwd]").val() != $(this).find("input[name=repeatPwd"]).val()){ 
     alert ('All fields are required. Please Correct and resubmit'); 
     return; 
    } 
    // do the post and replace the context of the section with the returned markup. 
    $.ajax({ 
     url:window.location.toString, 
     type:"POST", 
     data:$(this).serialize(), 
     success:function(htmlStr){ 
      $('#sect_info').html(htmlStr); 
     } 
    )}; 
}); 

編輯:一[名=密碼]的方括號的是帶引號

+0

它就像一個魅力!非常感謝您的時間和您的回覆! –

+0

我編輯了你的代碼,因爲它有語法錯誤! –

0

你只需要表單發佈自己。爲此只需使用沒有「操作」的表單或將操作指向自己。 例如,如果在那裏的形式是文件,它的命名「myform.php」,那麼你可以使用:

<form action="http://www.mywebsite.com/myform.php" method="post"> 

然後,在您檢查myform.php的$ _ POST(或$ _REQUEST的開頭如果你想)

if (!empty($_POST['user'])) { 
/* do stuff */ 
} 

<form action="http://www.mywebsite.com/myform.php" method="post"> 
/* the form's inputs goes here */ 
+0

嗨,亞歷克斯!感謝您的時間!我正在那樣做,但仍然無效。我已經標記爲Orangepill的答案,其實際效果很好!再次感謝你的時間 –

+0

沒問題丹尼爾,只是一句小心,我喜歡Ajax,但是你不應該過度使用它,記住通常會打破後退按鈕,而且速度也會變慢。該表單發佈後,這是一種非常常見的技術。 –