对不起,如果这已经被问过很多次了,但我无法让它工作。我正在尝试建立一个宁静的网站,我有一个简单的表格:<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 也能被接受?
                    
                    
                3 回答
                            慕运维8079593
                            
                                
                            
                        
                        
                                                
                    TA贡献1876条经验 获得超5个赞
更改您的 ajax 代码
$('#btnSubmit').on('click', function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/new.php",
data: $("#myformid").serialize(),
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
您还需要在形式上进行一些更改
<form action="new.php" method="post" id="myformid">
Name <input type="text" name="name">
<input id="btnSubmit" type="button" value="Test">
您可以在 php 文件中获取 POST 数据,例如 $_POST['name']
- 3 回答
 - 0 关注
 - 281 浏览
 
添加回答
举报
0/150
	提交
		取消
	