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
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
本文标签: Passing javascript object to php file using ajax post methodStack Overflow
版权声明:本文标题:Passing javascript object to php file using ajax post method - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742419250a2471323.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论