gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:46:01 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com