我拼命尝试使用 ajax post 方法将 json 对象传递给 php 文件,对其进行解码并传回一些东西。 Php的json_last_error显示4,表示Syntax error。
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
关于php - 使用ajax post方法将javascript对象传递给php文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18648229/