[英]Send Post data to the server with JavaScript
假設我有一張桌子
--
-- Database: `demo`
--
-- -------------------------------------------------------
CREATE TABLE IF NOT EXISTS `members` (
`member_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`member_id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`user_id`,`name`) VALUES
(1,'Admin');
-- --------------------------------------------------------
這是插入數據的 php 代碼
<?php
error_reporting(~E_NOTICE);
if(isset($_POST['add'])){
$name=strip_tags($_POST['name']);
$sth=$db->prepare("INSERT INTO members(name)VALUES(?)");
$sth->bindparam(1,$name,PDO::PARAM_STR);
$sth->execute();
}
?>
和 html 表單來處理用戶輸入
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=0.1,shrink-to-fit=no">
<title>demo</title>
</head>
<body>
<form method="post" name="myForm">
<input type="text" name="name" placeholder="Enter name">
<button type="submit" name="add">Submit</button>
</form>
</body>
</html>
如何通過使用 javascript 來實現相同的目標? 我聽說過 xhttpRequest 和 formData 對象,但我不知道如何使用它們來使事情變得更好
這是一個使用FormData和Fetch API 的快速 JavaScript 示例。
const myForm = document.getElementById('myForm'); // Grab the form;
//Handle the submit listener;
myForm.onsubmit =e=>{
e.preventDefault(); // Disable default form actions.
let formData = new FormData(); // Initiate a new FormData Object
let name = e.target.name.value; // Grab the "name" input value from the form.
formData.append('name',name); // Append the varible to the FormData object.
fetch('http://localhost/testpost.php',{
'method':'POST', // Use POST method for this fetch request.
'body':formData // Set the formData as the fetch request's body.
})
.then(res=>res.text())
.then(data=>console.log(data));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.