成功将PHP值传递回AJAX函数

时间:2019-06-01 01:21:57

标签: php html ajax callback

我正在构建墙上帖子的AJAX时间轴,并且具有以下功能来检查新帖子,然后将新帖子发布到墙上,类似于Twitter的工作原理:

wall_posts.php

$news = tz::shared()->news->getNew(25);

<div id="wall_posts">
    <?php foreach ($news as $news_post) { ?>
        <div class="wall_post"><?php echo $news_post['message']; ?></div>
    <?php } ?>
</div>

jQuery:

function checkForNewPosts() {

    // This represents the last record in the table AKA the "most recent" news
    var lastCustomerNewsID = <?php echo $news[0]['id']; ?>;

    $.ajax({
        url: "example.com/ajax.php",
        method: "post",
        data:{
            lastCustomerNewsID: lastCustomerNewsID,
        },
        dataType:"text",
        success:function(data)
        {
            $('#wall_posts').prepend(data);
        }
    });

}

setInterval(checkForNewPosts, 10000);

上面带有索引0的新闻PHP数组表示它是数组/表中的最后一个/最近的ID

PHP(ajax.php):

if ($_POST) {

    $lastCustomerNewsID = $_POST['lastCustomerNewsID'];

    $new_posts = tz::shared()->news->getNewForWall($lastCustomerNewsID);

    $output = '';

    if ($new_posts) {

        foreach ($new_posts as $new_post) {

            $output .= "<div class='wall_post'>";
                $output .= $new_post['message'];
            $output .= "</div>";

        }

    } else {

    }

    echo $output;

}

注意-函数getNewForWall提取ID大于传递的参数的记录

这在收到新帖子时很好用,但是问题是每次函数运行时,我需要从ajax.php中返回的新记录中将“最新ID”更新为“最新ID”,因为当前一次它是第一时间获取最新职位,并不断地将其视为新职位。

如何在每次运行时将最新的“ last id”从ajax.php中的数组传递回AJAX函数?我可以将单独的变量传递回AJAX函数吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

首先,我认为这里的PHP应该返回JSON而不是HTML信息 jQuery应处理JSON以生成HTML信息

PHP代码如下所示(这是一个示例)

AttributeError: module 'discord.ext.commands.converter' has no attribute 'GuildConverter'

现在,我们可以通过计时器和翻页检查是否有新文章。 然后,您可以使用maxpage来确定是否存在下一页。

<?php
$page   = $_POST['page'];
$method = $_GET['method'];

if ($method == "list") {
    $limit  = 20;
    $offset = ($page - 1) * $limit;

    $post = new Post();

    // Calculate offsets according to page limits and page numbers and query articles
    //Let's assume that the field of content is "content"
    $offset    = ($page - 1) * $limit;
    $post_list = $post->offset($offset)->limit($limit)->select();
    $total = $post->offset($offset)->limit($limit)->count(); //Statistics of all entries 

    //Get the largest ID by ID sort
    $last_id = $post->order('id desc')->find();
    $last_id = $last_id['id'];
    echo json_encode([
        'last_id'   => $last_id,
        'post_list' => $post_list,
        "maxpage"=>ceil($total / $limit), //Calculate the maximum number of pages
    ]);
} elseif ($method == 'last_check') {
    $post = new Post();
    //Get the largest ID by ID sort
    $last_id = $post->order('id desc')->find();
    $last_id = $last_id['id'];
    echo json_encode([
        'last_id' => $last_id,
    ]);
}