javascript - 在数据库中查找不成功后,如何用已插入的文本替换表单?
问题描述
我在 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。但它不会重新填写表格。
解决方案
首先,您必须更改您的 HTML 以包含该id
属性,例如:
<form method="post" action="input.php" id="Form">
<input type="text" class="form-control" id="txtName" name="txtName" maxlength="20" required style="margin-bottom:20px">
<input type="email" class="form-control" id="txtEmail" name="txtEmail" aria-describedby="emailHelp" required style="margin-bottom:20px">
<input type="submit" class="btn btn-success" id="btnsubmit" value="Zgłoś się" />
</form>
然后,您必须将您的逻辑移动到与表单容器(此处)相同的文件中Participate.php
,并删除失败的重定向。否则,您将看不到任何结果,因为重定向会阻止进一步的 JavaScript 代码运行。
// Updated to prevent syntax errors with multiline strings
echo "<script>"
. "window.alert('This mail already exist.');"
. "document.getElementById('txtName').value = 'nothing';"
. "</script>";
推荐阅读
- c# - 为什么引用的类验证属性不活动?
- python-requests - Python获取请求打印特定键和值
- youtube-api - 已达到 YouTube 数据 API 限制!我怎样才能增加这个限制?
- c - cmocka.h:虽然安装了 cmocka,但没有这样的文件或目录——IBM watson 嵌入式 C 客户端库
- java - 为什么 bigDecimal 的 scale() 方法与 stripTrailingZeros() 方法结合时返回负值?
- json - 如何将 TimezoneDB 时间检索到 Swift 标签
- angular - Angular 7,仅在生产中获得“无法读取 null 的属性‘appendChild’”
- python - 使用 WIN64 的 Python 3.7.3 蓝牙上最新的 STRAIGHT SCOOP 是什么
- django - 如何防止内联字段引用 Django Admin 中最新创建的对象
- r - 如何将 CSV 文件上传到 R,其中一行包含 ["123"、"456"、"789"] 形式的列表?