【问题标题】:Pass data to front end without timer无需计时器将数据传递到前端
【发布时间】:2018-09-01 02:51:46
【问题描述】:

我正在创建一个博客项目。我希望每次创建新帖子时,用户不必刷新页面即可查看帖子,它只会附加到已经存在的帖子。这就是目前正在做的事情

function postTin() {
$.ajax({
    type:'POST',
    url: "frextra.php",
    data:"ins=passPost",
    success: (function (result) {
        $("#post").html(result);
    })
})
}

postTin(); // To output when the page loads
setInterval(postTin, (5 * 1000)); // x * 1000 to get it in seconds

这里所做的是每 5 秒页面会重新加载发布的数据,在这种情况下它还会添加新发布的数据

我想要的是这个: 我不想使用计时器,我希望仅在数据库中添加新帖子时才加载请求。在这里被困了两个星期。搜索了一圈,没有看到任何帮助。

【问题讨论】:

标签: javascript php jquery ajax


【解决方案1】:

如果没有计时器,我不知道你怎么能做到这一点。所以这是我的解决方案,你需要调整你的代码:

添加与页面最新发布日期对应的发布参数

data: "ins=passPost&date=" + $('#posts-list li:first-child').data('date')

假设您的 HTML 中有类似的内容

<!-- Posts ordered from newest to oldest -->
<ul id="posts-list">
    <li data-date="2018-03-22 15:20">
        <!-- Here the Post HTML code -->
    </li>
    <!-- Here the remaining Posts -->
</ul>

在 PHP 中,您使用 post 参数 date 并请求数据库以获取更新的帖子,例如

'... AND date_added > ' . some_db_escape($_POST['date']) . '...'

在 ajax 成功函数中,您需要预先添加来自 PHP 的数据

$('#posts-list').prepend(result);

PHP 发送的数据必须是类似于上面 HTML 的 &lt;li&gt; 元素的字符串,表示从最新到最旧的较新帖子

<li data-date="2018-03-23 10:43">
    <!-- Here the Post HTML code -->
</li>
<li data-date="2018-03-22 18:00">
    <!-- Here the Post HTML code -->
</li>
<!-- etc. -->

【讨论】:

    【解决方案2】:

    您可以设置一个间隔来获取最新的帖子 ID,并检查它是否与您当前加载的最新帖子相同。

    $.ajax({
        type: 'GET',
        url: "latestpost.php",
        success: (function (result) {
            doStuff(result)
        })
    })
    
    
    function doStuff(latestIdInDatabase) {
        // Here you do whatever you want
    
        // latestIdInDatabase is the latest entry, they should be integer or whatever in
        // order to compare them
        if (currentLatestId < r) {
            /// do stuff
            // Like telling the user to realod because there is a new entry
            // Or make anoher call to get that from your current post to the latest
            // and using jquery or any framework print it
        }
    }

    latestpost.php 应该返回类似于最新帖子 ID 的内容。

    无论哪种方式,我认为正如 Luis Felipe De jesus Munoz 所说,您需要 websockets,或者干脆不重新加载,人们可能正在使用该网站,而您只是重新加载而不说什么,告诉用户有新帖子并按顺序要查看它们,它们必须重新加载。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-24
      • 2020-09-21
      相关资源
      最近更新 更多