php - php文件未从axios post请求接收数据
问题描述
php
文件未从axios
发布请求接收数据。表单提交后显示未定义的错误。我在 react 中创建了表单js
。所有字段和状态变量都正确显示。
axios({
method: 'post',
url: 'http://tulisuites.com/form.php',
headers: { 'content-type': 'application/json' },
data:JSON.stringify(this.state)
})
.then(result => {
this.setState({
mailSent: result.data.sent
});
console.dir(this.state);
})
.catch(error => this.setState({ error: error.message }));
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Content-Type: application/json");
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);
$subject = "Enquiry form";
$to = "sample@domainname.com";
// data
$msg = $_POST['name'] . $_POST['email'] . $_POST['organisation'] . $_POST['contactno'] . $_POST['message'];
// Headers
$headers = "MIME-Version: 1.0\r\n";
$headers.= "Content-type: text/html; charset=UTF-8\r\n";
$headers.= "From: <admin@tulisuites.com>";
mail($to, $subject, $msg, $headers);
?>
解决方案
如果您通过 ajax 以正确的 JSON 格式将数据发送到服务器,它应该已经在您的全局$_POST
变量中。var_dump($_POST)
您可以通过使用查看其内容来确保您正在获取数据。如果它包含您的数据,则无需从输入流中读取值,对其进行解码然后覆盖您的全局变量,您只需使用以下行:
$msg = $_POST['name'] . $_POST['email'] . $_POST['organisation'] . $_POST['contactno'] . $_POST['message'];
它应该工作。
此外,您可以使用filter_input(INPUT_POST, "variable")
每个参数,而不是$_POST["variable"]
确保它们已设置并防止错误。
推荐阅读
- javascript - 单行函数体周围更漂亮的箭头括号
- excel - Excel 计算唯一值整列,例如 A:A
- sql - 用 NULL 初始化数字
- sql - 相关子查询的更新语句太慢
- c# - 多用户访问时如何使用变量静态列表
- hibernate - Grails:向父域对象添加多个子元素的痛苦
- android - GoogleFit 区分来自不同设备的数据
- amazon-web-services - 使用 Cloudwatch 计划规则预热 Lambda 函数
- javascript - 如何将 react-s3-uploader 与 reactjs 一起使用?
- ios - 为什么 iOS 中不允许 JIT?我们可以启用它吗?