对不起,如果这已经被问过很多次了,但我无法让它工作。我正在尝试建立一个宁静的网站,我有一个简单的表格:
<form action="/my/path" method="post" id="myformid">
Name <input type="text" name="name">
<input type="submit" value="Test">
</form>
我使用 Javascript 转换用户输入的数据,然后使用 Ajax 将它们发送到我的 php 文件:
function postData() {
$('#myformid').on('submit', function(event) {
event.preventDefault();
const json = JSON.stringify($("#myformid").serializeArray());
$.ajax({
type: "POST",
url: "/my/path",
data: json,
success: function(){},
dataType: "json",
contentType : "application/json"
});
});
}
我尝试读取 php 上的数据,例如:
$data = json_decode(file_get_contents('php://input'), true);
$name = $data["name"];
如果我使用 Postman 之类的工具在请求正文中发送 JSON,则代码可以完美运行,但是从我使用 Ajax 测试的结果来看,json 数据作为 POST 数据到达,我可以使用 $_POST["name"] 读取它,但不是像我一样使用'php://input'。
我该如何修复它以便即使通过 Javascript 发送 JSON 也能被接受?
白衣非少年
慕运维8079593