jquery中的json问题

时间:2011-05-13 14:01:52

标签: php jquery ajax

我使用以下代码:

$(document).ready(function() {
        $.ajax({
            url: "tiles/chartValue.php",
            datatype: 'json',
            type: 'POST',
            success: function(data){                
                $.each(data, function(key, value) { 
                  alert(key + ': ' + value); 
                });
                       });
                });

这是chartValue.php

<?php
    include("../functions.php");
    $DAO=new DBUtil();
    $DAO->initDB("../db/connection.properties");
    $k=$DAO->getChart();
    echo json_encode($k);
?>

这是functions.php

的getChart函数
public function getChart()
{
    $sql = "SELECT a.total, round( (b.active *100) / total ) active_user, round( (c.inactive *100) / total ) inactive_user
        FROM 
        (               
            SELECT IFNULL( count( * ) , 0 ) total FROM ashekan_info
        )a, 
        (               
            SELECT IFNULL( count( * ) , 0 ) active FROM ashekan_info WHERE is_active =1
        )b, 
        (               
            SELECT IFNULL( count( * ) , 0 ) inactive FROM ashekan_info  WHERE is_active =0
        )c";

        $result=mysql_query($sql,$this->connect()) or die(mysql_error());   
        $row = mysql_fetch_assoc($result);  
        $json = array('total'       =>$row['total'],
                  'active_user' =>$row['active_user'],
                  'inactive_user'   =>$row['inactive_user']
                 ); 
        return $json;

}

我在firebug中得到的结果是{“total”:“1”,“active_user”:“0”,“inactive_user”:“100”}

问题是它在警告框中显示每个字符。即:{,“,t等等。

我怎么能得到1,0,100?提前致谢。

3 个答案:

答案 0 :(得分:7)

只是一个猜测......

您有datatype: 'json',但JS区分大小写,正确的参数为dataType。所以它忽略了这一点,采用文本,你的each调用正在迭代字符串的字符。

答案 1 :(得分:0)

因为您从AJAX调用中得到的答案仍然是一个字符串。 首先用JQuery.ParseJson解析它,然后迭代解析后的变量。

答案 2 :(得分:0)

我认为你需要的是:

header("Content-type: application/json");

之前

echo json_encode($k);