繁体   English   中英

PHP未从Ajax发布接收JSON

[英]PHP not receiving JSON from Ajax post

我试图通过Ajax将一些JSON发送到PHP处理代码。 这是我的JavaScript

var j = {"a":"b"};
var xmlhttp;
if (window.XMLHttpRequest){
    xmlhttp = new XMLHttpRequest();
} else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
};
xmlhttp.onreadystatechange = function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        console.log(xmlhttp.responseText)
    };
};
xmlhttp.open("POST", "server.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xmlhttp.send({
    "json": j
});

PHP

$json = $_POST["json"];
echo $json;

但这呼应null 我做错了什么? 这似乎应该工作。 谢谢!

请不要jQuery。 如果您投了反对票,请告诉我为什么,这样我可以改善。

您的j变量是一个对象。 您需要先将其编码为json字符串,然后再发布。

好的,我已经从头开始重新编写了答案。

像这样更新您的server.php

<?php

// Request Handler
if (count($_POST))
{
    $json = isset($_POST['json']) ? $_POST['json'] : '';
    if (!empty($json))
    {
        $jsonObj = json_decode($json);
        print_r($jsonObj);
    }
    else
    {
        echo "No json string detected";
    }
    exit();
}

?>

像这样更改您的ajax请求:

<script type="text/javascript">

var j = {"a":"b"};

var xmlHttp = new XMLHttpRequest();
var parameters = "json="+ encodeURIComponent(JSON.stringify(j));
xmlHttp.open("POST", "server.php", true);

xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameters.length);
xmlHttp.setRequestHeader("Connection", "close");

xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        console.log(xmlHttp.responseText);
    }
}

xmlHttp.send(parameters)

</script>

这是一个工作示例:

在此处输入图片说明


因此,在PHP脚本中,我正在打印$jsonObj及其内容。 如果要在脚本中使用它; 您可以这样做:

例如

<?php

if ($jsonObj->a == 'b') {
    // do something ?
}

?>

如果要使用关联数组(而不是对象),可以执行以下操作:

更改: $jsonObj = json_decode($json); 发送至: $jsonObj = json_decode($json, true);

现在您可以执行以下操作:

<?php

if ($jsonObj['a'] == 'b') {
    // do something ?
}

?>

Javascipt:

encode en JSON  with JSON.stringify(j);

如果j在字符串中包含&而不是分隔符de data:

j.split("&").join("%26");

在PHP中

$json = $_REQUEST['json'];
$json = str_replace("%26","&",$jsonData);
$json = html_entity_decode($json,ENT_NOQUOTES,'UTF-8');
$data = json_decode($json,true);

json的值作为数据数组。

要正确提交JSON,应为:

xmlhttp.send(JSON.stringify({"json": j});

然后对于PHP:

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

问题在于,发送JSON(如果它是正确的JSON请求)时,PHP不会自动对其进行解析。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM