【发布时间】:2018-06-30 16:17:55
【问题描述】:
我是 php、JSON 和 js 的新手。
我的问题是我的 php 以某种方式从 js 接收到 unquote json 字符串。
在通过函数JSON.stringify 传递它之后,我已经打印了 json 字符串。我得到一个带引号的普通 json 字符串
这是我的 js 脚本:
function post()
{
var test1 = {
name:"marzzuq",
age:16
};
myjson = JSON.stringify(test1);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","post.php",true);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.send(myjson);
console.log("\nsend ok: " + myjson);
}
我从 console.log 得到这个
send ok: {"name":"marzzuq","age":16}
这是我的 php 脚本:
<?php
$rawdata = file_get_contents('php://input');
`echo $rawdata >> /tmp/test.txt`;
$JSON = json_decode($rawdata,true);
` echo test2 > /tmp/test.txt` ;
switch (json_last_error()) {
case JSON_ERROR_NONE:
`echo ' - No errors' >> /tmp/test.txt`;
break;
case JSON_ERROR_DEPTH:
`echo ' - Maximum stack depth exceeded' >> /tmp/test.txt`;
break;
case JSON_ERROR_STATE_MISMATCH:
`echo ' - Underflow or the modes mismatch' >> /tmp/test.txt`;
break;
case JSON_ERROR_CTRL_CHAR:
`echo ' - Unexpected control character found' >> /tmp/test.txt`;
break;
case JSON_ERROR_SYNTAX:
`echo ' - Syntax error, malformed JSON' >> /tmp/test.txt`;
break;
case JSON_ERROR_UTF8:
`echo ' - Malformed UTF-8 characters, possibly incorrectly encoded' >> /tmp/test.txt`;
break;
default:
`echo ' - Unknown error' >> /tmp/test.txt`;
break;
}
?>
在函数结束时,当我访问 /tmp/test.txt 时,我得到了这个:
{name:marzzuq,age:16}
为什么我得到一个不带引号的字符串?我应该得到正确的引用字符串?像这样:{"name":"marzzuq","age":16}
【问题讨论】:
-
在您的 bash 终端中尝试
echo {"name":"marzzuq","age":16}。看到问题了吗?我建议你使用像file_put_contents()这样的PHP 文件方法,而不是execution operators -
投票结束是一个错字
-
@Phil,不同的终端似乎有不同的行为。当我使用 windows 命令行时,它会将正确的 json 写入 txt 文件。当我使用 mintty 终端(由 GIT 提供的 windows git bash 终端)时,它会将
name:marzzuq age:16写入 txt 文件。从另一个菲尔。 :) -
@Phil
/tmp表示 *nix 系统。 -
感谢您的澄清。我没有注意到 echo {"name":"marzzuq","age":16} 会让我得到不带引号的字符串。是的,我的系统是freebsd。而上面的代码只是一个简单的代码,看看是否可以在我的服务器上发送和接收 JSON 数据。
标签: javascript php json