我有这段代码:
<?php $arr= array(
array
(
'name' => 'Sony PS4',
'quantity' => '1',
'unit_price' => '$250.00'
),
array
(
'name' => 'XBox 360',
'quantity' => '1',
'unit_price' => '$200.00'
));?>
然后我有这个Ajax请求行
<?php $encoded_json = json_encode($arr); echo '<script>'; echo 'var encodedStr = "'. $encoded_json. '"'; echo 'var params = "encodedValue=" + encodedStr'; //Ajax GET request with 'params' variable goes here, </script>';?>
这是ajax请求处理行:
<?php $encoded_value = $_GET['encodedValue']; json_decode($encoded_value); //this gives me null, rather than the original encoded array ?>
我的代码有问题吗?如何恢复原始数组?请给我任何指向正确方向的指示。
首先,您需要将JSON作为字符串发送到PHP。有很多方法可以做到这一点,比如JSON.stringify。然后,您应该检查是否有一个实际的JSON格式的字符串要解码。然后检查json_decode函数返回的值,如果该值不为真,则使用json_list_error函数检查错误
$encoded_value = $_GET['encodedValue'];
if (!$encoded_value) { die('No value to parse'); }
$result = json_decode($encoded_value);
if (!$result) { die(json_last_error()); }