admin管理员组

文章数量:1336659

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
Add a ment  | 

1 Answer 1

Reset to default 5

You 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

本文标签: Passing javascript object to php file using ajax post methodStack Overflow