javascript - 弹出消息无法显示来自 php mysql 的新更新记录

标签 javascript php jquery mysql

我制作了一个带有自动刷新功能的弹出消息,所以每隔几分钟弹出消息就会出现以显示记录。它奏效了。

以下是自动刷新的JavaScript代码:

$(document).ready(function() {
    setInterval(function() {
        $('#rtnotice').load('plugins/notice/n_notice_invoice.php').fadeIn("slow");
    }, 5000)
});

n_notice_invoice.php代码

    <script>
    $(document).ready(function(){
        $("#hide").click(function(){
            $("#noticearea").hide();
        });
    });
    </script>

<?php
    try{
    require_once "../../config/c_config.php";
    $db = dbConn::getConnection();
    $timestamp = $_REQUEST['term'];
    $sqlck = $db->prepare("SELECT COUNT(id_notice_alert) as ttlinv FROM str_notice_alert WHERE date_alert > '$timestamp'");
    $sqlck->execute();
    $resck = $sqlck->fetch(PDO::FETCH_ASSOC);
    if($resck['ttlinv'] == '0')
    {}else{
    ?>
    <div id="noticearea">
    <div id="modal">
            <div class="modal-content">
                <div class="header">
                    <div id="circle" align="center"><h1><?php echo $resck['ttlinv'];?></h1></div><div class="titlenotice"><h1>NOTICE ALERT<?php echo $timestamp; ?></h1></div>
                    <div class="break"></div>
                </div>
                <div class="copy">
                    <p>
                    <table width="100%" class="gridtable">
                    <tr><th>No</th><th>Name</th><th>Status</th><th>Location</th><th>Date</th></tr>
    <?php 
    $sqll = $db->prepare("SELECT * FROM str_notice_alert");
    $sqll->execute();
    while($resl = $sqll->fetch(PDO::FETCH_ASSOC)){ 
    ?>
    <tr><td align="center"><?php echo $resl['id_notice_alert']; ?></td><td><?php echo $resl['alert_name']; ?></td><td align="center"><?php echo $resl['alert_status']; ?></td><td align="center"><?php echo $resl['alert_location']; ?></td><td><?php echo $resl['date_alert']; ?></td></tr>
    <?php } ?>
    </table>
                    </p>
                </div>
                <div class="cf footer">
                    <button id="hide" class="btn">Close</button>
                </div>
            </div>
            <div class="overlay"></div>
        </div></div>
    <?php 

    $sqltrunc = $db->prepare("TRUNCATE TABLE str_notice_alert");
    $sqltrunc->execute();

    }$db = null;}
    catch (PDOException $e) {
    echo "Connection Error " . $e->getMessage();
    }
    ?>

弹窗显示后,会显示文件n_notice_invoice.php 已有记录,也可通过查询删除记录。在任何场合。但问题是,为什么记录没有更新/更改。 u除非我直接刷新文件n_notice_invoice.php,然后自动刷新显示最近的数据。

最佳答案

$timestamp = $_REQUEST['term'];

应在您每次调用该页面时更新。您应该使用将 $timestamp 作为参数传递的 Ajax 加载页面,而不是仅仅加载它。

为了得到你需要的东西,我可以建议你使用长轮询吗? PHP 长轮询或更好的 node.js。对于 php 例如“服务器”页面:

$timeStart = time();
// Create connection
$con = mysqli_connect('localhost','root','','polldb');

// Check connection
if (mysqli_connect_errno($con))
    die ('Failed to connect to MySQL: ' . mysqli_connect_error() );

// select where item is new
if(isset($_POST['timestamp'])){
    $timestamp = $_POST['timestamp'];
}else{
    // get current database time
    $row = mysqli_fetch_assoc(mysqli_query($con,'SELECT now() as now'));
    $timestamp = $row['now'];
}
$sql = "SELECT * FROM `notification` WHERE timestamp > '$timestamp'";

$newData = false;
$notifications = array();

// loop while there is no new data and is running for less than 20 seconds
while(!$newData && (time()-$timeStart)<20){

    // check for new data
    $result = mysqli_query($con,$sql);
    while($row = mysqli_fetch_assoc($result)){
        $notifications[] = $row;
        $newData = true;
    }
    // let the server rest for a while
    usleep ( 500000 );
}

// get current database time
$row = mysqli_fetch_assoc(mysqli_query($con,'SELECT now() as now'));
$timestamp = $row['now'];
mysqli_close($con);

// output
$data = array('notifications'=>$notifications,'timestamp'=>$timestamp);
echo json_encode($data);
exit;

和客户:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function(){
    pullNotification();
});

function pullNotification(timestamp){
    var data = {};
    if(typeof timestamp!='undefined')
        data.timestamp = timestamp;

    $.post('longpoll.php',data,function(msg){

        var newData = '';
        for(i in msg.notifications){
            newData+=msg.notifications[i].message+'\n';
        }
        if(newData!='')
            alert(newData);
        pullNotification(msg.timestamp);
    },'json');
}
</script>

这将检查数据库更新并将它们弹出。每 20 秒它会更新请求。显然,您必须根据自己的需要调整它。

关于javascript - 弹出消息无法显示来自 php mysql 的新更新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29727499/

相关文章:

php - MySql COUNT() 作为字段只返回一个条目

javascript - jquery 使用 AND 和 OR 运算符按属性选择第 2 部分

javascript - Angular 6 测试 Jasmine Karma : Override Provider Not working

javascript - 选择一个选项后取消突出显示下拉菜单

php - 使用简单 HTML DOM 将相对 URL 转换为绝对 URL?

php - ImageMagick 不正确的尺寸

javascript - 在 jQuery 中动态定义具有特定样式的类

jquery ui 选择菜单 : How do i set the dynamic width correctly?

javascript - 在 angularjs 中,当 ng-options 数组发生变化时,如何刷新 `select` ?

Facelets 中未定义 Javascript 方法