如何回显json对象而不用引号括起来?

时间:2011-10-03 16:45:57

标签: php string json

第一次与json打交道。我有一个php文件处理通过ajax发送给它的post变量,然后它将回显一个json_encoded数组。我无法通过它进行迭代,因为它用双引号括起来。我怎么解决这个问题?

jquery代码:

$j.ajax({
   type: 'GET',
   url: 'http://example.com/doaction.php',
   data: 'num=' + fileNum[1],
   success: function(jsonobj) {
     for (var key in jsonobj) {
       if (jsonobj.hasOwnProperty(key)) {
         var jsonob = jsonobj[key];
         console.log(key + " = " + jsonob);
       }
     }
   }
});

doaction.php中的php代码:

if ($_GET['num']) {
    $meta = file_meta($_GET['num']); // returns an array
    echo json_encode($meta);
}

file_meta函数:

function file_meta($num = 1) {
$num = '_' . $num;
$meta = array(
    'filename' . $num => array(
        'value' => ''),
    'link' . $num => array(
        'value' => ''),
    'description_' . $num => array(
        'value' => ''),
    'metadata' => array(
        'type' => 'checkbox',
        'label' => 'Indicate applicable competencies:',
        'items' => array(
            'core_teaching' . $num => array(
                'label' => 'Core Teaching',
                'value' => 0
            ),
            'teaching_learning' . $num => array(
                'label' => 'Teaching Learning',
                'value' => 0
            ), 
            'instructional_design' . $num => array(
                'label' => 'Instructional Design',
                'value' => 0
            ), 
            'assignment_and_evaluation' . $num => array(
                'label' => 'Assignment & Evaluation',
                'value' => 0
            ),
            'research' . $num => array(
                'label' => 'Research',
                'value' => 0
            ),
            'mentoring' . $num => array(
                'label' => 'Mentoring',
                'value' => 0
            )   
        )
    )
);

return $meta;

}

控制台中的结果不是我所期望的。它应该是键值对,但它是乱码,而不是如下所示。

 500 = ,
 501 = "
 502 = v
 503 = a
 .
 .
 .

我很确定这是因为json对象$.ajax()正在包含在引号中。当我将object没有引号直接分配给jsonobj时,我得到了正确的结果。当我直接从$.ajax()函数中调用file_meta()时,我得到了正确的结果:

var jsonobj = <?php $etc = file_meta(); echo json_encode($etc); ?>;
// iterate here...

然而,这不是我想要的,因为file_meta()需要与click事件中检索到的元素的值一起传递。通过$ _GET发送它是我所知道的唯一。

1 个答案:

答案 0 :(得分:4)

使用json_decode()将JSON字符串转换为PHP变量

$var = json_decode('{"file":{"test": 0}}');

在javascript使用中:

var decoded = eval('{"file":{"test": 0}}');

如果您使用的是jQuery库,请使用:

var json = '{"file":{"test": 0}}';
var decoded = $.parseJSON(json);
相关问题