[英]Ajax only gives data after page reload
我正在尝试为博客的非活动文章创建一个通知按钮,并且我不想让管理员重新加载他/她的页面以查看提交的新非活动文章,因此我想使用AJAX进行此操作。
我将html数据附加到:
<ul id="menu1" class="dropdown-menu list-unstyled msg_list" role="menu">
但是我的代码仅在页面重新加载后才加载新结果。
同样,每个循环将相同的数据重复两次。
怎么了
<script>
$.ajax({
type: "POST",
url: 'inc/file.php',
dataType: 'json',
success: function(response)
{
if (response) {
var html = '';
$.each(response, function(key, value){
html += "<li><a href='editArticle?id="+response.id+"&act='><span>"+response.title+"</span><span>"+response.story+"</span></a></li>";
})
$('#menu1').prepend(html);
$('#number').text(response.number);
}
}
});
</script>
这是我的file.php,仅提取一个数据:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/config/init.php';
require CLASS_PATH.'article.php';
$article = new Article();
$list = $article->getInactiveArticle();
$number = $article->countInactiveArticle();
$output = [];
foreach ($list as $lists) {
$output['title'] = $lists->title;
$output['id'] = $lists->id;
$output['story'] = $lists->story;
$output['number'] = $number[0]->inactive_articles;
}
echo json_encode($output);
尝试使用setTimeout()
函数。
function timeout() {
setTimeout(function(){
$.ajax...
timeout()
}, 3000);
}
您可以测试以下代码块。
每5秒检查一次并执行操作。
$(document).ready(function () {
var eint = window.setInterval(function () {
$.ajax({
type: "POST",
url: 'inc/file.php',
dataType: 'json',
success: function(response)
{
if (response) {
var html = '';
$.each(response, function(key, value){
html += "<li><a href='editArticle?id="+response.id+"&act='><span>"+response.title+"</span><span>"+response.story+"</span></a></li>";
})
$('#menu1').prepend(html);
$('#number').text(response.number);
}
}
});
},5000);
)};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.