javascript - 使用 javascript 将数据信息发布到 CGI 脚本
问题描述
我有这个非常简单的 HTML 表单。我想将输入传递给 CGI 脚本(Python),它将它们存储到 mysql 表中。
<!DOCTYPE html>
<html>
<body>
<h2>Cadastro</h2>
<form name="cadastro" id="cadastro" action="/cgi-bin/cadastro.py" method="POST">
<label for="nome">Nome completo:</label><br>
<input type="text" id="nome" name="nome" required><br>
<label for="mae">Nome completo da mãe:</label><br>
<input type="text" id="mae" name="mae" required><br>
<br><br>
<input type="submit">
</form>
</body>
</html>
该表单效果很好,数据正确存储到 mysql 表中。
但是,我想在单击提交按钮时发出“成功”消息,而不是将其重定向到 cgi 脚本。
我相信最简单的方法是使用 javascript。然后,我尝试将其添加到代码中:
<script>
const cadastro = document.getElementById("cadastro");
cadastro.addEventListener("submit", (e) => {
e.preventDefault();
const request = new XMLHttpRequest();
request.open("post", "/cgi-bin/cadastro.py")
request.send();
});
</script>
这是python脚本,以防万一:
print("Content-type: text/html\r\n\r\n")
import cgi, mysql.connector
db = mysql.connector.connect(
host = "xxx",
user = "yyy",
password = "aaa",
database = "bbb",
)
cadastro = cgi.FieldStorage()
def add_cliente(nome, mae):
cursor = db.cursor()
cursor.execute("INSERT INTO cadastro (nome, mae) VALUE (%s, %s)", (nome, mae))
db.commit()
return print(cursor.rowcount, "record inserted.")
add_cliente(cadastro.getvalue("nome"), cadastro.getvalue("mae"))
但是,用户输入在 mysql 表中存储为 NULL。有人可以帮忙吗?
解决方案
它归结为脚本不发送任何数据,因此是 NULL 值。如前所述,cgi 脚本运行良好。
这是一个示例 javascript 代码,从这里提取:
window.addEventListener( "load", function () {
function sendData() {
const XHR = new XMLHttpRequest();
// Bind the FormData object and the form element
const FD = new FormData( form );
// Define what happens on successful data submission
XHR.addEventListener( "load", function(event) {
alert( event.target.responseText );
} );
// Define what happens in case of error
XHR.addEventListener( "error", function( event ) {
alert( 'Oops! Something went wrong.' );
} );
// Set up our request
XHR.open( "POST", "https://example.com/cors.php" );
// The data sent is what the user provided in the form
XHR.send( FD );
}
// Access the form element...
const form = document.getElementById( "myForm" );
// ...and take over its submit event.
form.addEventListener( "submit", function ( event ) {
event.preventDefault();
sendData();
} );
} );
推荐阅读
- javascript - 如何在 file_get_contents 和 echo $content 之后为数字着色;
- entity-framework-core - Entity Framework Core 2.1 - FromSql 方法中的通用模型
- python - 在 django 和 aws 中使用 crontab 发送数千封电子邮件
- python - 如何将可能格式错误的 xml 解析为数据框?
- c# - 带有 Web 套接字 MatchingTweetReceived 的 Twitter 流未在 twitterinvl 中触发
- elasticsearch - 如何配置 Java RestClient 以与 ElasticCluster 通信?
- java - 如何更改 LocalDate 提供的月份的语言?
- .net - RSACng 设置盐值
- symfony - Symfony jmsserilaizerbundle 配置不起作用
- php - Symfony 上传时找不到文件异常