json_decode在json_encod-ed字符串上返回NULL

时间:2015-03-18 11:30:21

标签: php ajax json

我有这段代码:

<?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-request-processing生产线:

<?php $encoded_value = $_GET['encodedValue']; json_decode($encoded_value); //this gives me null, rather than the original encoded array ?>

我的代码有什么不对吗?如何取回原始阵列?请指出方向正确的方向。

1 个答案:

答案 0 :(得分:0)

首先,您需要将JSON作为字符串发送到PHP。像JSON.stringify这样有很多方法可以做到这一点。 然后你应该检查是否有一个实际的JSON格式字符串要解码。 然后检查从json_decode函数返回的值,如果值不为true,则使用json_last_error函数检查错误

$encoded_value = $_GET['encodedValue']; 
if (!$encoded_value) { die('No value to parse'); }
$result = json_decode($encoded_value); 
if (!$result) { die(json_last_error()); }
相关问题