javascript - 如何在 PHP 中检索使用 fetch() 从 React js 发送的数据?
问题描述
我想将我的表单数据从react js
应用程序发送到我的后端PHP
程序。为了发送数据,我使用了fetch()
in react js。以下是我的反应 js 代码:
import React, { Component } from 'react';
class Form extends Component{
constructor(props){
super(props);
this.state = {
username:''
}
}
submitHandler = async (event) => {
event.preventDefault();
console.log(this.state.username);
const data = this.state.username;
await fetch("http://localhost:9090/assign/getApi.php",{
method:'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({data})
}).then((res)=>console.log(res));
}
render(){
return(
<div className="form">
<form method="POST" onSubmit={this.submitHandler}>
<input type="text" placeholder="name" onChange={(event)=>{
this.setState({
username:event.target.value
});
}} value={this.state.username} />
<input type="submit" value="click" name="submit" />
</form>
</div>
);
}
}
export default Form;
如何在我的 PHP 代码中检索这些数据?目前,我只是这样做,但输出是空的Array()
<?php
print_r($_POST);
?>
解决方案
您应该在输入前添加一个名称。name="name"
<input type="text" name="name" placeholder="name" onChange={(event)=>{
this.setState({
username:event.target.value
});
}} value={this.state.username} />
如果你将使用 fetch 那么你应该路径参数:
await fetch("http://localhost:9090/assign/getApi.php",{
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
}),
body: "name= " + data
在 php 中:
<?php
$name = $_POST['name'];
echo $name;
推荐阅读
- sql-server - Azure 应用服务 Web API 连接到 SQL Server 数据库,使用 Azure AD 帐户/Windows 身份验证
- java - JsonMappingException:Spring Boot GET 请求中的无限递归(StackOverflowError)
- azure - Powershell 无法访问运行时环境变量
- javascript - 如何使用 TypeScript 运行顶级 async / await 函数?
- java - Android MediaPlayer 意外停止播放(未最终确定)
- javascript - 为什么在使用工厂函数和构造函数时,Chrome 控制台中的对象看起来不同?
- vba - 表单/查询对嵌入另一个表单后停止工作
- google-sheets - 批量大小计算数组、商、序列
- r - 在导入其他数值时处理“小于”和“大于”符号的最佳做法是什么?
- flutter - Flutter Widget 中的 didChangeDependencies 钩子包含不准确的类数据