如何正确使用 JSON.stringify 和 json_decode() [英] how to use JSON.stringify and json_decode() properly
问题描述
我试图通过以下方式将多维 Javascript 数组传递到我网站上的另一个页面:
Im trying to pass a mulitidimensional Javascript array to another page on my site by:
在数组上使用 JSON.stringify
using JSON.stringify on the array
将结果值分配给输入字段
assigning the resultant value to an input field
将该字段发布到第二页
对发布的值使用 json_decode
using json_decode on the posted value
然后 var_dump 进行测试
then var_dump to test
(直接回显发布的变量只是为了看看它是否通过完全没有)
(echo'ing the posted variable directly just to see if it came through at all)
第一页上的 JavaScript:
var JSONstr = JSON.stringify(fullInfoArray);
document.getElementById('JSONfullInfoArray').value= JSONstr;
php 在第二页:
$data = json_decode($_POST["JSONfullInfoArray"]);
var_dump($data);
echo($_POST["JSONfullInfoArray"]);
回声工作正常,但 var_dump 返回 NULL
The echo works fine but the var_dump returns NULL
我做错了什么?
这让我解决了:
$postedData = $_POST["JSONfullInfoArray"];
$tempData = str_replace("\\", "",$postedData);
$cleanData = json_decode($tempData);
var_dump($cleanData);
我不知道为什么,但帖子通过一堆\"字符分隔字符串中的每个变量
Im not sure why but the post was coming through with a bunch of "\" characters separating each variable in the string
使用 json_last_error()
解决这个问题,由 Bart 推荐,返回 JSON_ERROR_SYNTAX
Figured it out using json_last_error()
as sugested by Bart which returned JSON_ERROR_SYNTAX
推荐答案
您需要检查 $_POST["JSONfullInfoArray"]
的内容.如果某些内容没有解析 json_decode
将只返回 null
.这不是很有帮助,因此当返回 null
时,您应该检查 json_last_error()
以获取有关出错的更多信息.
You'll need to check the contents of $_POST["JSONfullInfoArray"]
. If something doesn't parse json_decode
will just return null
. This isn't very helpful so when null
is returned you should check json_last_error()
to get more info on what went wrong.
这篇关于如何正确使用 JSON.stringify 和 json_decode()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!