我无法将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
?>
答案 0 :(得分:1)
这不是有效的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"
}
答案 1 :(得分:1)
您上传的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
执行:
$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);
如果您有大量数据可能无法作为单个数组存入内存,您可以尝试:
[
character ,
字符,除非它是第一个对象]
character 答案 2 :(得分:0)
当你返回两个对象时,它们需要在一个数组中。
您的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"
}
]
答案 3 :(得分:0)
在此处调整您的代码:
<?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);
?>