【发布时间】:2012-02-12 19:09:06
【问题描述】:
我无法将 JSON 加载到我正在创建的应用中
$("#load_basic").click(function(){
$.ajax({
url: 'php/show.php',
method: 'get',
dataType: 'json',
success: function(json) {
$("#textarea").html(json.doc);
}
});
});
我来自 show.php 的 JSON 如下
{
"id": "1",
"title": "doc 1",
"doc": "Lorem Ipsum",
"lastsaved": "2012-02-12 08:33:49"
} {
"id": "3",
"title": "doc 2",
"doc": "another lorem ipsum document",
"lastsaved": "2012-02-12 08:39:31"
}
请任何人帮忙。首先,我试图在本地进行,我认为这可能是问题所在,但现在我已经在服务器上尝试过,但仍然没有乐趣。有什么想法吗?
这是用于创建 JSON 文件的 show.php 源代码
<?php
header('Content-type: application/json');
include 'db.php';
$query = 'SELECT * FROM docs';
$result = mysql_query($query) or die('<p class="db_error"><b>A fatal MySQL error occurred while trying to select <b>EVERYTHING</b> from the database.</b><br />Query: '.$query.'<br />Error: ('.mysql_errno().') '.mysql_error().'</p>');
while ($row = mysql_fetch_assoc($result)) {
$arr = array('id'=>$row['id'],'title'=>$row['title'],'doc'=>$row['doc'],'lastsaved'=>$lastsaved = $row['lastsaved']);
echo json_encode($arr);
}//end while
?>
【问题讨论】:
-
你得到什么输出?有什么事发生吗?
-
不,我在控制台或任何输出中都没有收到任何错误
-
如果这真的是你的 JSON 字符串,那么你有一个问题:它不是有效的 JSON:如果你想要一个项目列表,那么你应该有一个数组,并且项目应该由逗号。
-
为了消除你的 JSON 无效的事实,你可以创建一个 php 数组,然后使用 json_encode 返回一个有效的 JSON 字符串
-
继续使用 $arr[] = array(... 将行添加到 $arr,然后只调用一次 json_encode() 而不是在 while 循环内。
标签: php jquery ajax json getjson