Javascript到PHP,正确的json格式
我在将JSON字符串转换为PHP对象/数组时遇到问题。我在谷歌上搜索了很多,看了很多youtube教程,但还是遗漏了一些东西 JAVA脚本:Javascript到PHP,正确的json格式,javascript,php,json,object,Javascript,Php,Json,Object,我在将JSON字符串转换为PHP对象/数组时遇到问题。我在谷歌上搜索了很多,看了很多youtube教程,但还是遗漏了一些东西 JAVA脚本: xhr = new XMLHttpRequest(); xhr.open('POST', 'save.php'); xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); var json_string = '{"name":"Bandage","picture":
xhr = new XMLHttpRequest();
xhr.open('POST', 'save.php');
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
var json_string = '{"name":"Bandage","picture":"129"}';
xhr.send("item=" + json_string);
PHP:
$item则为空
有什么想法吗?如果我不使用json_解码功能,我就可以正确地发布内容。。有什么不对,格式应该是什么样子的,这样PHP json_解码可以将其解析为对象或数组?我还尝试了使用/json头,PHP中的stripslashes,没有结果。。
谢谢 很抱歉回复晚,新的internet连接出现问题。 谢谢你的帖子,我的工作原理如下: 脚本:
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
//document.getElementById('div1').innerHTML = xhr.responseText;
}
}
}
var postitem = '{"name":"Bandage","picture":"129"}'; // working
xhr.open('POST', 'save.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("item=" + postitem);
echo$obj->name 尝试JSON.stringify()将值转换为JSON表示法。您可以发布什么var_dump($_post['item']);phpyour
var json\u字符串的返回值是有效的json。。。但是你真的得到了$\u POST
数据吗。。。发布数据,如@juank said。作为application/x-www-form-urlencoded
发送的名称和值可能需要有效--xhr.send(“item=“+encodeURIComponent(json_字符串))代码>。这与它们是否首先编码为JSON无关代码>以获取任何详细信息。把这些贴在这里。
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
//document.getElementById('div1').innerHTML = xhr.responseText;
}
}
}
var postitem = '{"name":"Bandage","picture":"129"}'; // working
xhr.open('POST', 'save.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("item=" + postitem);
$obj = json_decode($item);