Php Ajax只在页面重新加载后提供数据

Php Ajax只在页面重新加载后提供数据,php,jquery,ajax,Php,Jquery,Ajax,我正在尝试为我的博客的非活动文章创建一个通知按钮,我不希望管理员重新加载他/她的页面以查看提交的新的非活动文章,所以我希望使用AJAX来完成这项工作 我将html数据预编到: 但我的代码只在重新加载页面后加载新结果。 此外,每个循环将相同的数据重复2次 怎么了 <script> $.ajax({ type: "POST", url: 'inc/file.php', dataType: 'json', success: function(res

我正在尝试为我的博客的非活动文章创建一个通知按钮,我不希望管理员重新加载他/她的页面以查看提交的新的非活动文章,所以我希望使用AJAX来完成这项工作

我将html数据预编到:

但我的代码只在重新加载页面后加载新结果。 此外,每个循环将相同的数据重复2次

怎么了

<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+"&amp;act='><span>"+response.title+"</span><span>"+response.story+"</span></a></li>";

            })
            $('#menu1').prepend(html);
            $('#number').text(response.number);

        }
    }
});
</script>
这是my 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函数

函数超时{ setTimeoutfunction{ $.ajax。。。 超时 }, 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+"&amp;act='><span>"+response.title+"</span><span>"+response.story+"</span></a></li>";

                    })
                    $('#menu1').prepend(html);
                    $('#number').text(response.number);

                }
            }
        });
    },5000);
)};

您应该尝试websocket或类似的实时数据提供商使用类似Facebook的通知和更新。关于您的第二个问题:响应的价值是什么?它是一个对象数组吗?根据数据的结构,您可能希望使用value.id和value.title等@showdev我已经编辑了我的代码。我只得到一个数据作为响应。他可能希望setInterval而不是setTimeout,但Lalabuy正在AJAX调用中再次调用timeout。如果AJAX调用需要3秒以上,我想这可能有助于避免重复超时。是的,代码每5秒检查一次,但5秒后它会继续附加到相同的数据。我的意思是我有3个数据,5秒后我得到6个数据。试试这个方法。$'menu1'.htmlhtml@Alisha注意到您正在使用,这会增加现有内容,而不是替换它。@Tuncay BAŞ是的,我知道了,但我知道相同的数据正在重复。我的意思是我只得到id为1的数据。