从 php 获取用 Ajax 发送的数据?

对不起,如果这已经被问过很多次了,但我无法让它工作。我正在尝试建立一个宁静的网站,我有一个简单的表格:


<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 也能被接受?


沧海一幻觉
浏览 244回答 3
3回答

白衣非少年

从文档的.serializeArray()。.serializeArray() 方法创建一个 JavaScript 对象数组,准备好编码为 JSON 字符串。在同一个页面给出的例子中,很明显你会在 php 中得到一个数组,要访问一个元素,你应该尝试-`$data[0]['name']`另外,你试过print_r($data),它是NULL吗??

慕运维8079593

更改您的 ajax 代码$('#btnSubmit').on('click', function(event) {&nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; type: "POST",&nbsp; &nbsp; &nbsp; &nbsp; url: "/new.php",&nbsp; &nbsp; &nbsp; &nbsp; data: $("#myformid").serialize(),&nbsp; &nbsp; &nbsp; &nbsp; dataType: "json",&nbsp; &nbsp; &nbsp; &nbsp; success: function(response) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(response);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });});您还需要在形式上进行一些更改<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']
打开App,查看更多内容
随时随地看视频慕课网APP