Iam desperately trying to pass a json object using ajax post method to a php file, decode it and pass something back. Php's json_last_error displays 4, which means 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"];
}
?>
Iam desperately trying to pass a json object using ajax post method to a php file, decode it and pass something back. Php's json_last_error displays 4, which means 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"];
}
?>
Share
Improve this question
asked Sep 6, 2013 at 0:56
salacissalacis
2051 gold badge3 silver badges11 bronze badges
2
- Any reason why you're not using jQuery? – Mahesh Commented Sep 6, 2013 at 1:01
- 4 I am totally new to that and I don't want to start all over using a framework I don't understand – salacis Commented Sep 6, 2013 at 1:06
1 Answer
Reset to default 5You have to encode it to json if you want to send it as json.
xmlhttp.send("data="+encodeURIComponent(JSON.stringify(json)));
currently what you have will send something like data=[Object object]
.
The variable json
is a JavaScript object which is not json. JSON is a data-interchange format which is basicly a subset of javascript. see http://json
var object = {"name" : "Darth Vader"};// a JavaScript object
var json = '{"name" : "Darth Vader"}';// json holds a json string
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742419251a4440349.html
评论列表(0条)