首先,我所有关于php,mysql和js的工作都是在本地服务器上进行的。我第一次把我的作品放到网上。但是我这样做遇到了一些问题。
问题是每当我提交表格时,我的帖子都不会添加任何评论。警报方法alert(response)
我附加到警报"[对象对象]"中。这是否意味着它是一个有效的 JSON?
alert(obj)
的第二个警报甚至不会触发
我还得到以下错误作为回报:
语法错误:JSON.parse:第 1 行第 2 列的意外字符 JSON数据
。tion(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+");var c,d=null,e=m.trim(...
负责 AJAX 提交的部分是:
$.ajax('../includes/verifyanswer.php',{
data:{
'answer_body': CKEDITOR.instances.content.getData(),
'userpost_post_id': <?php echo $postid;?>,
'users_user_id': <?php echo $userdata->user_id; ?>
},
type:"POST",
dataType:'json',
success:function(response){
alert(response);
var obj=$.parseJSON(response);
alert(obj);
$('#mainanswer').hide();
$('#answerform').hide();
$('#answerthisquestion').show();
var str="<div class='styleanswer' >"+obj[0]['answer_body']+"</div><div class='customcmntholder'></div><span id='customcomment' class='cmnt' onclick='letmecomment(event);'>Add a Comment...</span><form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post' name='cmntform'> <textarea data-id="+obj[0]['answer_id']+" class='customcmntform' placeholder=' add a comment......' ></textarea></form><hr>";
$('#answerwrapper').append(str);
$('#answerwrapper pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
},
error:function(response){
alert(response);
}
})
验证答案.php :
require_once '../core/init.php';
$answer=$_POST['answer_body'];
$post_id=$_POST['userpost_post_id'];
$answerer=$_POST['users_user_id'];
if(isset($answer,$post_id,$answerer)){
if(!empty($answer) && !empty($post_id) && !empty($answerer)){
$db=DB::getInstance();
$result=$db->post_and_fetch("CALL login.post_and_fetch_ans(?,?,?)",array($answer,$post_id,$answerer))->result();
echo json_encode($result);
}
}
说dataType:'json',
,jQuery会解析HTTP响应中的JSON,并将其转换为JavaScript数据结构,然后再传递给success
函数。
这意味着当你说var obj=$.parseJSON(response);
时,你隐式地将其转换回字符串(但不是 JSON 字符串,而是 "[object Object]"
),然后尝试将其解析为 JSON,但事实并非如此,因此失败。
您的 ajax 提交已经告知response
将以 JSON ( type:"POST",
) 的形式出现,因此您不需要var obj=$.parseJSON(response);
行。此外,调试代码的更好方法是使用 console.log
而不是 alert
,在 firebug (Firefox 的扩展名) ou 谷歌浏览器控制台中查找结果。
在你测试你设置的变量的 php 代码中,你应该测试$_POST
变量本身或使用提取。如果您愿意,您也可以加入这两个if
。
它会是这样的:
require_once '../core/init.php';
extract($_POST);
if(isset($answer_body,$userpost_post_id,$users_user_id) AND
!empty($answer_body) AND !empty($userpost_post_id) AND !empty($users_user_id)){
$db=DB::getInstance();
$result=$db->post_and_fetch("CALL login.post_and_fetch_ans(?,?,?)",array($answer_body,$userpost_post_id,$users_user_id))->result();
echo json_encode($result);
}
您可以使用 JSON.parse() 方法将 JSON 响应解析为 javascript 数组。
点击这里了解更多详情