我用
解析JSONeval()函数 `
我有错误
未捕获的SyntaxError:意外的标记ILLEGAL
这是我的javascript代码:
var commentPerpost = document.getElementById('commentPerpost');
var response = eval('('+receiveReq.responseText+')');
for(var i=0;i < response.Comment.comment.length; i++) {
commentPerpost.innerHTML += '<li><div id="Cclose" align="right">' +
'<input id="Userid" type="hidden" name="Userid" value="' + response.Comment.comment[i].iduser + '" /></div>' +
'<div id="Cprofil"><img src="../91mbr27pg09/foto_profil/' + response.Comment.comment[i].ava +
'" style="width: 40px; height: 40px;" alt="" />' +
'<h4 style="margin: 0; padding-top: 5px;">' + response.Comment.comment[i].username + '</h4></div>' +
'<div id="Cpost"><div style="max-width: 330px;">' + response.Comment.comment[i].comment +
'</div><div class="Cdatetime">' + response.Comment.comment[i].tgl + ' ' + response.Comment.comment[i].time +
'</div></div><div class="clearBoth BdrBottomN"></div></li>';
}
我的php代码是:
<?php
$json = '{"Comment": {';
if(!isset($_GET['idnews'])) {
} else {
$idnews = db_input($_GET['idnews']);
$last = (isset($_GET['last']) && $_GET['last'] != '') ? $_GET['last'] : 0;
$sql_comment = "SELECT c.id_user, c.id_comment,c.id_judul,c.email,c.tanggal,c.id_member,c.comment,m.id,m.username,m.foto_profil,k.id,k.judul FROM comment c, member m, k_news k WHERE c.id_user = m.id AND c.id_judul = k.id AND k.id = '$idnews' AND c.id_comment > '$last' ORDER BY c.tanggal ASC";
$qry_comment = db_query($sql_comment);
if(db_num_rows($qry_comment) > 0) {
$json .= '"comment":[ ';
while($data_comment=mysql_fetch_array($qry_comment)){
$json .= '{';
$json .= '"idcomment": "' . htmlspecialchars($data_comment['id_comment']) . '",
"iduser": "' . $data_comment['id_user'] . '",
"username": "' . $data_comment['username'] . '",
"comment": "' . htmlspecialchars($data_comment['comment']) . '",
"ava": "' . htmlspecialchars($data_comment['foto_profil']) . '",
"tgl": "' . tgl_indo($data_comment['tanggal']) . '",
"time": "' . time_indo($data_comment['tanggal']) . '"
},';
}
$json .= ']';
}
else {
$json .= '"comment":[]';
}
}
$json .= '}}';
echo $json;
?>
请帮助我如何解决错误?
答案 0 :(得分:2)
不要手动拼凑JSON!你在某个地方犯了一些错误并且产生了无效的JSON。让PHP使用json_encode
:
$data = array('Comment' => array());
while (...) {
$data['Comment'][] = array(...);
}
echo json_encode($data);