简体   繁体   English

php ajax-仅在返回的数据不为空时自动刷新div

[英]php ajax - auto refresh a div only if returned data is not empty

I am using bootstrap , php and mysql for an application . 我正在为应用程序使用bootstrap,php和mysql。 With this , whenever the users are logged in , the admin will post messages across to all users that will be displayed as an alert on the page . 这样,无论何时用户登录,管理员都将向所有用户发布消息,这些消息将在页面上显示为警报。 Below is my ajax code : 下面是我的ajax代码:

$.ajaxSetup(
    {
        cache: false,
        beforeSend: function() {
            $('#admin_message').hide();
        },
        complete: function() {
            $('#admin_message').show();
        },
        success: function() {
            $('#admin_message').show();
        }
    });
    var $admin_msg = $("#admin_message");
    $admin_msg.load("get_message_board.php");        
    var refreshId = setInterval(function()
    {
        $admin_msg.load('get_message_board.php');
    }, 10000);

Below is my alert holder holder 以下是我的警报持有人持有人

    <div class="alert alert-success" id="alert_holder">
<p id="admin_message" style="text-align: center;font-size: 20px"></p>
</div>

PHP SCRIPT : PHP脚本:

include './functions.php';

    $sql = "select message from msg_db3 where user_group ='".$_SESSION['active_user_group']."' order by id DESC LIMIT 1";
    $temp = return_results($sql);

    echo $temp['0']['message'];

Now i want to make sure that the div (with id='alert_holder') is hidden by default and shows up only if echo $temp['0']['message'] is not empty .If it is empty , it should be hidden . 现在我要确保div(id ='alert_holder')默认是隐藏的并且仅在echo $ temp ['0'] ['message']不为空时显示。如果为空,则应为被隐藏。 Also the transition is a bit odd since it shakes the entire page while bringing the alert up on the screen . 过渡也有点奇怪,因为它在摇动整个页面的同时将警报显示在屏幕上。

Please advice on the above . 请就以上建议。

THanks in advance . 提前致谢 。

EDIT: can you try with normal Ajax? 编辑:您可以尝试使用普通的Ajax吗?

$.ajax({
  url: "get_message_board.php"
})
.done(function( data) {
console.log(data);
 if(data.length>0){
       $('#admin_message').show();
     } else {
       alert('not found');
     }
}
});

Check your response length and show if it's not null 检查您的回复长度并显示是否为空

success: function(data) {
 if(data.length>0){
   $('#admin_message').show();
 }
}

In php script you can change to 在php脚本中,您可以更改为

if(isset($temp['0'])){
 echo $temp['0']['message'];
}

The main problem with your code is with 您的代码的主要问题是

complete: function() {
            $('#admin_message').show();
        },

This code will show #admin_message every time when ajax is completed. 每次ajax完成时,此代码都会显示#admin_message。 if you remove this unnecessary part you can make only my first change with if detection. 如果您删除了这个不必要的部分,则只能通过if检测进行我的第一个更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM