新消息到达时显示通知(闪烁选项卡)

时间:2014-07-31 08:33:54

标签: jquery ajax

我不确定代码是否正确。正如我在标题中提到的那样,当新消息到达时,想法是闪烁浏览器选项卡(如果它没有聚焦)。给定的代码(没有$("#full_chat").bind("DOMSubtreeModified",function())可以完成工作,但一旦焦点丢失,它总是会闪烁。请提出解决问题的方法。

<script>
setInterval(function refreshPage() { 

         var user=$("#head").text();

         $.post("retrieve.php",
                {                 
                    user:user
              },
              function(data,status){

                        $("#full_chat").append("<span class='you'>"+data+"</span>");
                        $('#full_chat').emoticonize();

                    $(window).blur(function() { //I want the notofication to show only when the tab has no focus

                         $("#full_chat").bind("DOMSubtreeModified",function(){//The notification should appear only when a message comes

        //Code for showing "New chat message!" using 'jquery.titlealert.js'

                        $.titleAlert("New chat message!", {
                        requireBlur:false,
                            stopOnFocus:true,
                            interval:700
                            });
                        });

                    });

              });

         }, 1500);
<script>

&#39; retrieve.php&#39;文件内容

   <?php session_start();
    $other_user=$_POST['user'];
    //$flag=$_POST['flag'];
    include_once('db.php');
    $uname=$_SESSION['username'];

    //date_default_timezone_set('Asia/Kolkata');


        $q="select message,sender,time from chat where username='$uname' and delivered=0  and      sender='$other_user' order by time ASC";
        $qe = mysqli_query($con,$q);
        $q1="UPDATE chat SET delivered=1  WHERE username='$uname' and sender='$other_user'" ;
        $qe1 = mysqli_query($con,$q1);
        while($r=mysqli_fetch_array($qe)) {
            echo "(".$r['time'].")  ". $r['sender'].": ".$r['message']."<br>";

        }
         mysqli_close($con); 
        ?>

2 个答案:

答案 0 :(得分:1)

请转义传递给mysql的variables并阻止sql注入。如果你正在使用javascript + php,请使用json格式在它们之间传递数据。

jquery在json中支持ajax请求,但你需要在jquery中切换到$.ajax函数。

<强> retrieve.php     

include_once('db.php');

//$flag     =   $_POST['flag'];
$returnData =   [];
$other_user =   mysqli_real_escape_string($con, $_POST['user']);
$uname      =   mysqli_real_escape_string($con, $_SESSION['username']);

$queryMessages  = "select message,sender,time from chat where username='".$uname."' and delivered=0  and sender='".$other_user."' order by time ASC";
$resultMessages = mysqli_query($con, $queryMessages);

if( mysqli_num_rows($resultMessages) >= 1 )
    {
        while ($r = mysqli_fetch_array($resultMessages)) {
            $returnData[] = "(" . $r['time'] . ")  " . $r['sender'] . ": " . $r['message'] . "<br>";
        }
        mysqli_query($con, "UPDATE chat SET delivered=1  WHERE username='".$uname."' and sender='".$other_user."'");
}

mysqli_close($con);

echo json_encode($returnData);

javascript方

setInterval(function refreshPage() {
    var userData = $("#head").text();
    $.ajax({
        url : 'retrieve.php',
        type : "POST",
        data : {
            user : userData
        },
        contentType : "application/json; charset=utf-8",
        dataType : "json",
        success : function (messages) {
            if( messages.length >= 1 )
            {
                $.each(messages, function(index) {
                    $("#full_chat").append("<span class='you'>" + messages[index] + "</span>");
                });

                $('#full_chat').emoticonize();
                $.titleAlert("New chat message!", {
                    requireBlur : true,
                    stopOnFocus : true,
                    interval : 700
                });
            }
        }
    });
}, 1500);

titleAlert插件有什么问题。它具有所有功能。这对我来说很好。

只需将选项requireBlur设置为true

即可
  

如果为true,则除非窗口失焦,否则将忽略该调用。   已知问题:Firefox不会将标签切换识别为模糊,并且   还有一些小的IE问题。

答案 1 :(得分:0)

稍微改变了我的代码,现在它完美地工作了:)

<强> retrieve.php

<?php session_start();
    $other_user=$_POST['user'];
    $flag=$_POST['flag'];
    include_once('db.php');
    $uname=$_SESSION['username'];

    //date_default_timezone_set('Asia/Kolkata');


    $q="select message,sender,time from chat where username='$uname' and delivered=0  and sender='$other_user' order by time ASC";
    $qe = mysqli_query($con,$q);
    $q1="UPDATE chat SET delivered=1  WHERE username='$uname' and sender='$other_user'" ;
    $qe1 = mysqli_query($con,$q1);
    if($r=mysqli_fetch_array($qe)) {
            echo "(".$r['time'].")  ". $r['sender'].": ".$r['message']."<br>";
    //modification: added an else statement("echo failed") for later use.
    }else {           
        echo "failed";  
    }
     mysqli_close($con); 
?>

<强>脚本

<script>
    setInterval(function refreshPage() { 

                 var user=$("#head").text();
                 $.post("retrieve.php",
                        {                 
                            user:user
                      },
                      function(data,status){
                                if($.trim(data)!="failed"){ //if not "failed" to execute query
                                        $("#full_chat").append("<span class='you'>"+data+"</span>");
                                        $('#full_chat').emoticonize();
                                        window.onblur = function () {  //**if window has no focu**s
                                                $('#full_chat').bind("DOMSubtreeModified",function(){  //**if any change happened to the div**
                                                    $.titleAlert("New Message!", { //**display notification**
                                                    requireBlur:true,                                               
                                                    stopOnFocus:true,
                                                    //duration:10000,                                               
                                                    //interval:500
                                                });
                                                });


                                    }
                                }
                    }); }, 1500);
    </script>
相关问题