【问题标题】:Passing javascript object to php file using ajax post method使用ajax post方法将javascript对象传递给php文件
【发布时间】:2013-09-06 00:56:53
【问题描述】:

我正在拼命尝试使用 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"];
}
?>

【问题讨论】:

  • 你为什么不使用jQuery?
  • 我对此完全陌生,我不想使用我不了解的框架重新开始

标签: php javascript ajax json


【解决方案1】:

如果你想将它作为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

【讨论】:

  • 你说得对,我对此做了一个输出,而 Object 对象就是之前传输的对象。您的解决方案效果很好!你能解释一下为什么我必须使用 JSON.stringify 编码我的 var json,我认为它已经是 json。
  • +1 对于这个答案和问题。我刚刚遇到了同样的问题。
猜你喜欢
  • 2012-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 2015-05-16
相关资源
最近更新 更多