我试图通过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
});
和
$json = $_POST["json"];
echo $json;
但这与null
有着相似之处。我做错了什么?这看起来应该管用。谢谢!
请不要jQuery。如果你投反对票,请告诉我为什么我可以提高。
发布于 2014-04-30 13:07:23
您的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);
To:$jsonObj = json_decode($json, true);
现在你可以这样做了:
<?php
if ($jsonObj['a'] == 'b') {
// do something ?
}
?>
发布于 2014-04-30 13:15:56
Javascipt:
encode en JSON with JSON.stringify(j);
如果j包含& in字符串而不是分隔符de data:
j.split("&").join("%26");
in php
$json = $_REQUEST['json'];
$json = str_replace("%26","&",$jsonData);
$json = html_entity_decode($json,ENT_NOQUOTES,'UTF-8');
$data = json_decode($json,true);
json作为数据数组的值。
发布于 2014-04-30 13:20:55
要正确提交JSON,应该是:
xmlhttp.send(JSON.stringify({"json": j});
然后,对于PHP:
$json = json_decode(file_get_contents('php://input'));
问题是,当发送JSON (如果是正确的JSON请求)时,PHP不会自动解析它。
https://stackoverflow.com/questions/23388932
复制相似问题