php - 使用ajax post方法将javascript对象传递给php文件

标签 php javascript ajax json

我拼命尝试使用 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/

相关文章:

ajax - CRUD中的R-功能和披露漏洞之间的界线在哪里?

javascript - CORS保护 : What is the point of HTTP_ORIGIN

php - 尝试使用 XHR 2 和 PHP 上传多张图片

php - 迁移不要把 "unique"放在我的 table 上

javascript - js.erb 不执行 javascript 但已处理 rails

javascript - async.each 有问题,回调在完成任务之前被调用

javascript - polymer 自动节点查找不起作用

javascript - 从另一个 div 的导航更改一个 div 的内容

php - 在 Laravel 4 中将变量从路由组传递到路由函数

php - 如何在数组中存储 POST 元素