[英]CodeIgniter: How to send a javascript variable to contoller and back to the view?
I am trying to achieve live updating on variables in my viewers and It is almost done. 我正在尝试在查看器中实现对变量的实时更新,并且几乎完成了。 The problem is that I want to compare the result now from the variable so I can print one message or another.
问题是我现在想比较变量的结果,以便可以打印一条消息或另一条消息。 I am using append to put the result into a div and echo it to show the number of comments but I can't get it to compare with the if statement in the file.
我正在使用append将结果放入div中并回显它以显示注释数,但是我无法将其与文件中的if语句进行比较。
Here is the JavaScript: 这是JavaScript:
<script>
var myVar = setInterval(function(){get_msg_count()}, 1000);
function get_msg_count() {
$.ajax ({
data: {}, // not really needed
type: 'POST',
url: '<?php echo site_url("blog/getCommentCount");?>', // page to return your msg count
success: function(response) {
$('#noOfComments').html(response);
}
}); // End $.ajax
} // End Function
</script>
Here is the view for the comments: Where it is the actual problem of trying to compare the variable. 这是评论的视图:这是尝试比较变量的实际问题。
<h2>Comments - {<div class="noOfComments" id="noOfComments"></div>}</h2>
<?php $variable = '<div id="noOfComments</div>' ?>
<?php if ($variable >= 1): ?>
<div class="comment-box">
<div id="responds"></div>
{comments}
<div class="single-comment">
<h5>{name}</h5><span class="pubdate"> - {pubdate}</span>
<hr/>
<p>{comment}</p>
</div>
{/comments}
</div>
<?php else: ?>
<div class="alert alert-info">
Sorry, I didn't manage to find any comments :(
</div>
<?php endif; ?>
and this is the controller: 这是控制器:
public function getCommentCount()
{
$comments = new Comment_model();
$noOfComments = $comments->where('blog_id', '2')->count();
echo json_encode($noOfComments);
}
Any ideas how to send it to the file and use the variable ? 任何想法如何将其发送到文件并使用变量? Thanks
谢谢
You must declare your response for json data. 您必须声明对json数据的响应。
controller 控制者
public function getCommentCount()
{
$comments = new Comment_model();
$noOfComments = $comments->where('blog_id', '2')->count();
/**
* declare ajax data here
* if your $noOfComments will show value
* ex : $noOfComments = 10
*/
$result['comments_count'] = $noOfComments;
echo json_encode($noOfComments);
}
And the javascript 和JavaScript
success: function(response) {
$('#noOfComments').html(response.comments_count);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.