我无法弄清楚为什么JSON不在我的评论系统中工作。任何帮助将不胜感激。
目前,当我提交评论表单时,ajax-loader会闪烁并旋转,但评论不会加载,我会得到"意外标记"语法错误。当我刷新页面时,会显示评论。
这是我的AJAX事件处理程序,它直接进入我的控制器(代码片段后面):
($('document').ready(function(){
$("button.submit").bind('click', function (e){
e.preventDefault();
var form = $('form');
var submit = $('button#submit');
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="/img/ajax-loader.gif" />');
$.ajax({
type: 'POST',
cache: false,
url: '?comment='+comment+'&item='+item+'&author='+author+'&rating='+rating,
data: form.serialize(),
dataTYPE: 'json',
success: function( data ){
comment_insert( jQuery.parseJSON( data ) );
console.log( "ResponseText: " +data );
form.trigger('reset');
$("#flash").hide();
}
});
});
});
function comment_insert( data )
{
var insert = '';
insert += '<article>';
insert += '<p>';
insert += ''+data.comment+'';
insert += '—';
insert += ''+data.author+'';
insert += ' | <a href="/item/reply"> Reply</a>';
insert += '</p>';
insert += '</article>';
$('.comment_block').prepend( insert );
}
控制器:
if($this->request->is('post')) {
$comments = ItemComments::create($this->request->data);
$comments->author_id = $this->user->id;
$comments->comment = $this->request->data['comment'];
$comments->item_id = $this->request->data['item'];
$comments->author_id = $this->request->data['author'];
$comments->rating = $this->request->data['rating'];
$comments->save();
echo json_encode($comments);
}
查看页面:
<div class="col-lg-12">
<h4>Comments and questions:</h4>
<?php if (count($comments)): foreach ($comments as $feedback): ?>
<article>
<p>
<?=$feedback->comment?>
—
<a href="/users/<?=$feedback->author->url?>">
<?=$feedback->author->firstname?>
<?=$feedback->author->lastname?>
<?=$feedback->id?>
</a>|
<a href="/item/reply">Reply</a>
</p>
</article>
<?php endforeach;?>
<?php else: ?>
<div class="col-lg-12">
<div class="well-sm text-center">
<i class="fa fa-comments fa-2x"></i>
<h4>No comments yet.</h4>
</div>
</div>
<?php endif; ?>
<div class="comment_block"></div>
<div id="flash"></div>
</div>