我正在以这种方式在javascript中创建一个json
jsonArr.push({
position: 'WN',
wind: windWN,
wave: waveWN,
sea: seaWN
});
var myJsonString = JSON.stringify(jsonArr);
我通过jsonData:jsonData:Ext.encode(myJsonString)
当我发送它时,我的json数组看起来像这样:
在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]);
它给了我正确的结果!
阵列( [position] => Ë [wind] => 3 [wave] =>五 [sea] => 6)
你有解释吗?
编辑:我通过制作另一个json_decode
来使其工作$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata,true);
$rawpostdata3 = json_decode($rawpostdata2,true);
但我真的不明白......
答案 0 :(得分:3)
首先,创建json字符串:
var myJsonString = JSON.stringify(jsonArr);
然后再将结果字符串编码为json:
Ext.encode(myJsonString)
因此,您必须在PHP中json_decode()
两次。
答案 1 :(得分:1)
尝试使用$ _POST代替file_get_contets()
,这会为您提供string。
答案 2 :(得分:1)
你需要对json_decode的结果进行类型转换,如下所示:
<?php
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = (array) json_decode($rawpostdata,true);
?>
我希望这对你有用..干杯...... !!