【发布时间】:2018-01-23 03:53:33
【问题描述】:
我是 PHP、JSON、js 的新手。
我有一个将 JSON 字符串发送到 PHP 的 js 程序
在 PHP 中使用 json_decode fn 时遇到一些问题。
我尝试将从JS接收的字符串保存到一个文件中,并且json字符串是正确的,没有任何问题。
但是当我尝试使用 json_decode 时,函数挂起(我认为,因为函数调用下面的任何东西都没有被调用,所以我所有的 echo/print 都没有给出任何东西。
下面是我的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);
}
下面是我的php脚本:
<?php
$rawdata = file_get_contents('php://input');
file_put_contents('/tmp/test.json', $rawdata);
$jsson = json_decode($rawdata);
file_put_contents('/tmp/test3.json', $jsson);
`echo test >> /tmp/test.txt`;
?>
我尝试过使用 htmlentities 和 html_entity_decode:$result= htmlentities((string)$rawdata);
$result2 = html_entity_decode((string)$rawdata);
并在json_decode 上使用结果,但它不起作用。
fr $rawdata 的长度是 27(使用 strlen),这是正确的。
我尝试打印 json_last_error,但就像我说的那样,json_decode 行下方的所有代码都停止工作,所以什么都不会打印。
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;
}
谁能帮帮我?
【问题讨论】:
-
@marekful:我明白了。但即使我删除了该行,json_decode 以下的任何内容仍然无法正常工作。我试过打印这样的东西:
echo yes sucess >> /tmp/test.txt;在 json_decode 之后,但它不打印 -
我已经在这里给你一个详细的例子来说明如何做到这一点:stackoverflow.com/questions/48374719/… 但你忽略了它。
-
@billynoah 我试过你的方法,但也许我做错了什么,因为它不起作用。我会再试一次。谢谢。顺便说一句,您是否删除了您对另一个问题的评论?
标签: javascript php json