javascript - 奇怪的行为 json_decode

标签 javascript php ajax json

我正在以这种方式在 javascript 中创建一个 json

jsonArr.push({
            position: 'WN',
            wind: windWN,
            wave: waveWN,
            sea:  seaWN
        });
        var myJsonString = JSON.stringify(jsonArr);

我使用 jsonData 通过 AJAX 方法发送它:jsonData:Ext.encode(myJsonString)

当我发送它时,我的 json 数组看起来像这样: enter image description here

在 PHP 方面,我获取 Json 并以这种方式对其进行解码:

$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata, true); 

我尝试了 print_r( $rawpostdata2[1]); 并得到了 '{' 作为“字符串”的第二个字符,我不明白为什么。

在另一边,我尝试了 print_r($rawpostdata),将结果剪切/粘贴到 $string 中,然后像这样重新测试我的 json_decode:

$rawpostdata = file_get_contents("php://input");
// print_r($rawpostdata);
$string = '[{"position":"N","wind":"2","wave":"65","sea":"65"},{"position":"E","wind":"3","wave":"5","sea":"6"},{"position":"S","wind":"56","wave":"4","sea":"8"},{"position":"W","wind":"1","wave":"56","sea":"84"},{"position":"NE","wind":"5","wave":"6","sea":"65"},{"position":"ES","wind":"6","wave":"45","sea":"6"},{"position":"SW","wind":"69","wave":"8","sea":"4"},{"position":"WN","wind":"7","wave":"8","sea":"56"}]';
$rawpostdata2 = json_decode($string,true); 
print_r ($rawpostdata2[1]);

它给了我正确的结果!

Array ( [position] => E [wind] => 3 [wave] => 5 [sea] => 6 )

你有什么解释吗?

编辑:我通过制作另一个 json_decode 使其工作

$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata,true); 
$rawpostdata3 = json_decode($rawpostdata2,true);

可是我不是很懂...

最佳答案

首先,您创建 json 字符串:

var myJsonString = JSON.stringify(jsonArr);

然后将结果字符串再次编码为 json:

Ext.encode(myJsonString)

因此,您必须在 PHP 中 json_decode() 两次。

关于javascript - 奇怪的行为 json_decode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28151207/

相关文章:

javascript - 使用 javascript 随着时间的推移改变背景图像?

php - SQL 插入日期总是出现 NULL

php - 用 php 或 javascript 替换 Img 位置/src?

javascript - Bootstrap 列表组菜单在单击时展开,但不会折叠

javascript - 无法添加到 Application Insight 中的自定义遥测初始值设定项

javascript - AngularJS ng-重复过滤器: {visible: true} does not follow property change

php - is_dir 不识别文件夹

php - Wordpress:使用ajax更改查询的循环?

javascript - 用于处理 Ajax 数据的设计模式。正确的方法是什么?

javascript - 从ajax调用结果更新qtip内容