在数据库中查找不成功后,如何用已插入的文本替换表单?

我在Participate.php文件中具有以下形式的代码:


<form method="post" action="input.php" id="Form">

            <input type="text" class="form-control" name="txtName" maxlength="20" required style="margin-bottom:20px"> 

            <input type="email" class="form-control" name="txtEmail" aria-describedby="emailHelp" required style="margin-bottom:20px">

            <input type="submit" class="btn btn-success" id="btnsubmit" value="Zgłoś się" />

        </form>

提交失败后(我检查插入的邮件是否已存在于数据库中),如果不存在,我想重新填写表单值。这是input.php代码:


<?php


$name = $_POST['txtName']; 

$mail = $_POST['txtEmail']; 

$description = $_POST['txtDescription'];

$connect = new PDO("mysql:host=4*****3;dbname=3*****b", "3***b", "****");

$connect->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );


$q=$connect->prepare("SELECT mail FROM konkurs WHERE mail LIKE (?)");

$q->bindValue(1, $mail);

$q->execute();

$row_cnt = $q->rowCount();

    if($row_cnt == 0){

        $query = $connect->prepare("insert into konkurs(name,mail,description)

        values(?, ?, ?)");

        $query->bindValue(1, $name);

        $query->bindValue(2, $mail);

        $query->bindValue(3, $description);

        try {

            $query->execute();

            echo ("<script LANGUAGE='JavaScript'>

            window.alert('Sent.');

            window.location.href='index.html';

            </script>");

            exit;

            } catch (PDOException $e) {

            die($e->getMessage());

            } 

    } else {

        echo ("<script LANGUAGE='JavaScript'>

            window.alert('This mail already exist.');

            window.location.href='Participate.php';

            document.getElementById('txtName').value = 'nothing';

            </script>");

        }


?>

问题是在未成功完成升级后将其重定向到Participate.php。但是它不会重新填写表格。


MM们
浏览 135回答 1
1回答

白衣染霜花

首先,您必须更改HTML以包含该id属性,例如:<form method="post" action="input.php" id="Form">&nbsp; &nbsp; <input type="text" class="form-control" id="txtName" name="txtName" maxlength="20" required style="margin-bottom:20px">&nbsp;&nbsp; &nbsp; <input type="email" class="form-control" id="txtEmail" name="txtEmail" aria-describedby="emailHelp" required style="margin-bottom:20px">&nbsp; &nbsp; <input type="submit" class="btn btn-success" id="btnsubmit" value="Zgłoś się" /></form>然后,您必须将逻辑移至与表单容器相同的文件(在此处Participate.php),并删除失败的重定向。否则,您将看不到可见的结果,因为重定向将阻止进一步的JavaScript代码运行。// Updated to prevent syntax errors with multiline stringsecho "<script>"&nbsp; &nbsp; &nbsp;. "window.alert('This mail already exist.');"&nbsp; &nbsp; &nbsp;. "document.getElementById('txtName').value = 'nothing';"&nbsp; &nbsp; &nbsp;. "</script>";
打开App,查看更多内容
随时随地看视频慕课网APP