首页 > 解决方案 > 使用 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。有人可以帮忙吗?

标签: javascriptpythonhtmlmysql

解决方案


它归结为脚本不发送任何数据,因此是 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();
  } );
} );

推荐阅读