无法使用jquery检索json数据

时间:2011-03-09 23:28:54

标签: php jquery json getjson

我是一个新手,我一直在检索json数据。

以下是我的index.php:

<script type="text/javascript" src="jquery-1.3.2.min_2.js"> 
$("document").ready(function() {

    $.getJSON("data.php",function(jsondata){
    $("#content").html(jsondata[0].content);    

    });
});
</script>
</head>
<body>
<div id="content"></div>
<div class="lg"></div>
</body>

在我的data.php中,我正在使用标准的编码方式和发送数据:

// execute query 
        $result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); 
         $row = mysql_fetch_row($result);
         $jsonserver[$i] = $row;
    }
    echo json_encode($jsonserver); 
    header('Content-type: application/json');
    mysql_free_result($result); 
    // close connection 
    mysql_close($con);  

我正在使用mysql数据库。 当我打开localhost / data.php时,浏览器会显示json数据。 但如果我打开localhost / index.php我不会得到任何所需的输出。 请解释。 谢谢!

2 个答案:

答案 0 :(得分:1)

您需要将所有标题放在页面上的任何'echo'之前

这样:

header('Content-type: application/json');
echo json_encode($jsonserver); 

答案 1 :(得分:0)

嘿     你没有正确关闭脚本标签

<script type="text/javascript" src="jquery-1.3.2.min_2.js"></script>
<script type="text/javascript">
$("document").ready(function() {
  $.getJSON("data.php",function(jsondata){
        $("#content").html(jsondata[0].content);
    });
});
</script>