【发布时间】:2013-03-31 18:55:51
【问题描述】:
我正在创建一个评论发布系统,允许用户使用 php mysql jquery 和 ajax 以及使用 Json 编写 cmets 但是当我插入 Json 并使用 firedebug 调试系统时遇到问题,我收到错误消息:SyntaxError: JSON.parse: unexpected character 谁能帮我解决这个错误
这是我使用 Json 的代码@line 42
$(document).ready(function() {
//this will fire whene the page will completly been loaded
$('#comment-post-btn').click(function(){
comment_post_btn_click();
});
});
function comment_post_btn_click()
{
// text within the text area
var _comment = $('#comment-post-text').val();
var _userId = $('#userId').val();
var _userName = $('#userName').val();
if(_comment.length > 0 && _userId != null )
{
// proceed with the ajax callback
$('#comment-post-text').css('border', '1px solid #e1e1e1');
$.post("ajax/comment_insert.php",
{
task : "comment_insert",
userId :_userId,
comment :_comment
}
)
.error(
function(data)
{
console.log("Error" );
})
.success(
function(data)
{
comment_insert(jQuery.parseJSON(data));
console.log("Response text: " + data )
}
);
console.log(_comment + " UserName: " + _userName + " User id: " + _userId );
}
else
{
$('#comment-post-text').css('border', '1px solid #ff0000');
console.log("the text area was empty");
}
// remove the text from the textarea
$('#comment-post-text').val("");
}
function comment_insert(data)
{
var t = '';
t+= '<li class="comment-holder" id="'+data.comment_id+'">';
t+= '<div class="user-img">';
t+= '<img src="'+data.profile_img+'" class="user-img-pic" />';
t+= '</div>';
t+= '<div class="comment-body">';
t+= '<h3 class="username-field">'+data.userName+'</h3>';
t+= '<div class="comment-text">'+data.comment+'</div>';
t+= '</div>';
t+= '<div class="comment-buttons-holder">';
t+= '<ul>';
t+= '<li class="delete-btn">X</li>';
t+= '</ul>';
t+= '</div>';
t+='</li>';
$('.comments-holder-ul').prepend(t);
}
comment_insert.php
<?php
if(isset($_POST['task']) && $_POST['task'] == 'comment_insert')
{
require_once("db_connect.php");
$userId = (int)$_POST['userId'];
$comment = addslashes( str_replace( "\n", "<br>", $_POST['comment']));
$std = new stdClass();
$std->comment_id = 24;
$std->userId = $userId;
$std->comment = $comment;
$std->userName = "georges matta";
$std->profile_img = "images/default_img.jpg";
require_once("comments.php");
if(class_exists('Comments'))
{
$commentInfo = Comments::insert($comment.$userId);
if($commentInfo!=null)
{
}
}
**echo json_encode($std);**
}
else
{
header("Location: /");
}
?>
【问题讨论】:
-
ajax/comment_insert.php返回的响应很可能是无效的 json。请向我们展示该输出的样子, -
你在你的 php 中使用 json_encode 吗? jQuery 以严格的方式解析 JSON 数据。尝试使用 json_encode,它总是适用于 jQuery
-
我编辑了我的问题,是的,我正在使用 json_encode
-
还有什么
echoing?Comment::insert有调试输出吗? -
您是否尝试过清理缓冲区并将内容类型设置为“application/json”?请分享您的 JSON 示例
标签: php jquery mysql ajax json