简体   繁体   English

Php ajax一次又一次地获取相同的文件html

[英]Php ajax fetching same file html again and again

I am working on notifications in php.我正在处理 php 中的通知。 In header file, I have written this function:在头文件中,我写了这个函数:

  $(document).ready(function() {      
      setInterval(getNotifys, 10000);      
      function getNotifys(){
            $.ajax ({                  
            method: "POST",
            url : 'get_notification.php',          
            success : function(data){
                console.log(data);            
                $('.notifications').html(data);                
            }
        });  
     }
 });    

And here is get_notification.php;这里是 get_notification.php;

<?php
include("global.php");
if($logged==0){
    header("location:".$baseurl."login.html");
    exit();
}
$data=mysqli_query($con,"select * from notifications where admin=1 and resolved=0") or die (mysqli_error());
$count = mysqli_num_rows($data);
?>
<span class="badge badge-danger" style="margin-bottom:25px"><?php echo $count; ?></span>

It works perfectly over most of the pages, but in some pages, it occurs that instead of displaying count to notification icon, it shows whole page HTML.它可以在大多数页面上完美运行,但在某些页面中,它会显示整个页面的 HTML,而不是显示通知图标的计数。 Even when I console in success function, It consoles whole page HTML.即使我在成功功能中进行控制台,它也会控制台整个页面的 HTML。 I am so confused why is it happening.我很困惑为什么会这样。 Any ideas?有任何想法吗?

use json and create that span stuff in your javascript code.使用 json 并在您的 javascript 代码中创建跨度内容。

    <?php
include("global.php");
if(!$logged) {
    http_response_code(401); // catch this error in ajax
    exit();
}

$data = mysqli_query($con,"select * from notifications where admin=1 and resolved=0");

if(!$data) {
    http_response_code(500); // catch this error in ajax
    exit(); 
}

$count = mysqli_num_rows($data);

echo json_encode(['count' => $count]);

JS: JS:

      $(document).ready(function() {      
      setInterval(getNotifys, 10000);      
      function getNotifys(){
            $.ajax ({                  
            method: "POST",
            url : 'get_notification.php',          
            success : function(data){
                let data = JSON.parse(data);
                console.log(data);
                $('#notifications_count').html(data.count);                
            },
            error: function(jqXHR, textStatus, errorThrown) {
              console.log(textStatus, errorThrown);
            }
        });  
     }
 });

HTML: HTML:

<span class="badge badge-danger" style="margin-bottom:25px" id="notifications_count"></span>

Did not test this, but this shows you how you could do it.没有对此进行测试,但这向您展示了如何做到这一点。

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

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