【问题标题】:How to post a form to same page loaded dynamically如何将表单发布到动态加载的同一页面
【发布时间】:2013-07-27 07:07:50
【问题描述】:

提前感谢您的宝贵时间。

我有一个 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 找不到表单元素。

那么:我如何发布表单并将其结果显示到我之前提到的那个部分?

对不起,我的英语很差。如果您需要更多详细信息或更多代码或其他任何内容,请告诉我。

再次感谢!

【问题讨论】:

  • 你有一些实际的 jQuery 代码要展示吗?
  • 仅供参考:echo 并不是真的要回显大量未动态构建的预定义 HTML。您可能需要考虑在&lt;table&gt; 之前关闭您的PHP ?&gt;,然后在表格&lt;/table&gt; 之后重新打开它&lt;?php。这样您就不必担心正确转义引号或使用另一种类型。它还将允许您的编辑器提供适当的代码突出显示,因为它不再只是一个大字符串。
  • 谢谢你们的回复和你们的时间。不错的提示 War10ck 谢谢!

标签: php jquery html ajax forms


【解决方案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);
        }
    )};
});

编辑:[name=pwd] 的方括号之一在引号之外

【讨论】:

  • 它就像一个魅力!非常感谢您的宝贵时间和回复!
【解决方案2】:

您只需要将表单发布到自己。为此,只需使用没有“动作”的表单或将动作指向自身。 例如,如果表单所在的文件名为“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 */

【讨论】:

  • 嗨,亚历克斯!谢谢你的时间!我正在这样做,但它仍然不起作用。我已将 Orangepill 的回复标记为答案,它实际上效果很好!再次感谢您的宝贵时间
  • 没问题 Daniel,请注意,我喜欢 Ajax,但你不应该过度使用它,记住通常会破坏后退按钮,而且速度较慢。将表单发布到自身是一种非常常见的技术。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-20
  • 1970-01-01
  • 2012-09-03
  • 2015-05-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多