首页 > 解决方案 > 如何通过 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));

标签: javascriptphphtmlfetch-api

解决方案


推荐阅读