我用这种方式在javascript中创建一个json
jsonArr.push({
position: 'WN',
wind: windWN,
wave: waveWN,
sea: seaWN
});
var myJsonString = JSON.stringify(jsonArr);
我通过带有jsonData的AJAX方法发送它:
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]);
它给我正确的结果!
数组(
[位置] => E
[风] => 3
[wave] => 5
[海] => 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()
。