【问题标题】:Send Post data to the server with JavaScript使用 JavaScript 将 Post 数据发送到服务器
【发布时间】:2021-04-04 10:13:45
【问题描述】:

假设我有一张桌子

--
-- 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 对象,但我不知道如何使用它们来使事情变得更好

【问题讨论】:

    标签: javascript php html mysql


    【解决方案1】:

    这是一个使用 FormDataFetch 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));
      
      
    }
    

    【讨论】:

    • sofanati UltraDraft UncaughtTypeError: Cannot set property 'onsubmit' of null
    • @williamwilliams 请将 id="myForm" 添加到 HTML 中的表单元素标签中。
    猜你喜欢
    • 1970-01-01
    • 2018-04-17
    • 2012-12-29
    • 2011-09-12
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    相关资源
    最近更新 更多