javascript - 如何通过 Fetch API 使用 POST 到 MySql
问题描述
我正在尝试使用 Fetch API、PHP 和 SQL 将数据发布到数据库。它不起作用,但我不确定问题出在哪里。
我要发布的输入:
<form id="postData" action="api/postWords.php" onsubmit="submitForm(event, this)">
<div>
<input type="text" name="values" id="WordValue">
</div>
<input type="submit" value="SEND POST">
</form>
Fetch API,我正在尝试发布表单
function submitForm(e, postData){
e.preventDefault();
document.getElementById('postData').addEventListener('submit', postData);
fetch('api/postWords.php', {
method: 'POST',
type: 'JSON',
body: ({WordValue: postData.values.value})
}).then(function(response) {
return response.json();
}).then(function(data) {
//Success code goes here
alert('form submited')
.then(result => alert(JSON.stringify(result, null, 2)))
}).catch(function(err) {
//Failure
alert('Error')
});
}
带有 SQL 语句的 PHP 文件:
<?php
if (!isset($_POST["WordValue"])) // prints out error if projectname is not set
{
die();
}
require_once("db.php");
$status = 200; // OK
$Words = $_POST["WordValue"];
for ( $i = 0; $i < count( $WordValue ); $i++ )
{
$WordValue = $Words[$i];
if ( !empty( $Words ) )
{
$result = $mysqli->query("INSERT INTO words (Words) VALUES ('$Words')");
if ( !$result )
{
$status = 300; // OK
}
}
else
{
$status = 301;
}
}
echo json_encode( array('status'=>$status));
解决方案
推荐阅读
- mysql - 查找,必要时在一条 SQL 语句中插入
- javascript - 如何在 React Router 中包含 props 回调
- javascript - 如何在 JavaScript 中制作“类型效果”?
- google-apps-script - 谷歌表单上传文件夹视图/树
- pandas - 使用 sklearn 进行逻辑回归的情绪分析
- amazon-web-services - 通过指定日期条件(DateGreaterThan、DateLessThan)限制 AWS 开发人员高级用户访问
- python - 为什么每次单击按钮时我的 tkinter GUI 都会闪烁?
- html - 标题/部分粘贴到页面顶部
- postgresql - 当我有高度值属性时,如何将 2D OSM 多边形转换为 3D?
- robotframework - 重定向 uri-RequestLibarry-Robot 框架