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

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

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

再次感谢!

4

2 回答 2

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] 的方括号之一在引号之外

于 2013-07-26T20:45:19.757 回答
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 */
于 2013-07-26T20:35:33.900 回答