我拼命地尝试使用 ajax post 方法将 json 对象传递给 php 文件,对其进行解码并传递回一些东西。PHP 的json_last_error显示 4,这意味着语法错误。
this.send = function()
{
var json = {"name" : "Darth Vader"};
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","php/config.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data="+json);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result").innerHTML=xmlhttp.responseText;
};
};
};
<?php
if(isset($_POST["data"]))
{
$data = $_POST["data"];
$res = json_decode($data, true);
echo $data["name"];
}
?>
如果要将其作为json发送,则必须将其编码为json。
xmlhttp.send("data="+encodeURIComponent(JSON.stringify(json)));
目前您拥有的内容将发送类似 data=[Object object]
.
变量 json
是一个不是 json 的 JavaScript 对象。JSON是一种数据交换格式,基本上是javascript的一个子集。见 http://json.org
var object = {"name" : "Darth Vader"};// a JavaScript object
var json = '{"name" : "Darth Vader"}';// json holds a json string