我在将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数组,如下所示。
[{
"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_encode()
,而不是分别回显每个数组。例如代替:
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
Do:
$arr = array();
while ($row = mysql_fetch_assoc($result)) {
$arr[] = array('id'=>$row['id'],'title'=>$row['title'],'doc'=>$row['doc'],'lastsaved'=>$lastsaved = $row['lastsaved']);
}//end while
echo json_encode($arr);
如果你有很多数据可能无法作为单个数组放入内存,你可以尝试:
- 回波
[
字符 - 对于要解析的每个对象:
- 回显
,
字符,除非它是第一个对象 - 对象的echo JSON
- 回显
- 回波
]
字符
这不是有效的JSON。对象之间缺少逗号。
...
"lastsaved": "2012-02-12 08:33:49"
} {
^ Missing comma
您可能想要发送一个对象数组,并引用json[0].doc
,例如:
[{ ... }, { ... }]
或者只发送一个对象,并参考json.doc
:
{
"id": "1",
"title": "doc 1",
"doc": "Lorem Ipsum",
"lastsaved": "2012-02-12 08:33:49"
}
当您返回两个对象时,它们需要在一个数组中。
您的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"
}
]
在此处调整代码:
<?php
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
?>
应成为
<?php
$json_output = array();
while ($row = mysql_fetch_assoc($result))
{
$json_output[] = array('id'=>$row['id'],'title'=>$row['title'],'doc'=>$row['doc'],'lastsaved'=>$lastsaved = $row['lastsaved']);
}//end while
echo json_encode($json_output);
?>