PHP脚本未接收到发布的JSON

PHP script not receiving posted JSON

本文关键字:JSON 脚本 PHP      更新时间:2023-09-26

我在以下JavaScript中遇到问题,其中数据是JavaScript对象:

var ajax_send = function(data) {
        var httpRequest;
        makeRequest('/prototype/test.php', data);
        function makeRequest(url, data) {
            if (window.XMLHttpRequest) {
                httpRequest = new XMLHttpRequest();
            } else if (window.ActiveXObject) {
                try {
                    httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } 
                catch (e) {
                    try {
                        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                    } 
                    catch (e) {}
                }
            }
            if (!httpRequest) {
                alert('Giving up :( Cannot create an XMLHTTP instance');
                return false;
            }
            httpRequest.onreadystatechange = alertContents;
            httpRequest.open('POST', url);
            httpRequest.setRequestHeader('Content-Type', 'application/json');
            httpRequest.send(JSON.stringify(data));
        }
        function alertContents() {
            if (httpRequest.readyState === 4) {
                if (httpRequest.status === 200) {
                    alert(httpRequest.responseText);
                } else {
                    alert('There was a problem with the request.');
                }
            }
        }
    };

PHP是:

$data = $_POST['data'];
$obj = json_decode($data);
echo $obj;

在开发工具中,请求负载看起来不错,但这似乎不是PHP想要的。PHP脚本中没有任何内容,响应为空。

我做错了什么?

当您使用Content-Type: application/json发送POST请求时,PHP的工作方式有点不同。

你需要这样访问它:

$postData = json_decode(file_get_contents('php://input'));

而不是通常的CCD_ 2。

如果你想把它作为一个将被填充到$_POST的常规表单发送,你需要这样设置你的标题:

httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

并像这样填充您的字段:

key=value&key2=value2&key3=value3

etc

在Symfony上,您可以使用内部生成file_get_contents('php://input')$request->getContent();)。然后解码结果。

$requestData = $request->getContent(); // this makes file_get_contents('php://input')
$data = json_decode($requestData, true);