每次将新事件添加到我的数据库时,我都会向我的用户显示通知。我的首页上有一个小图标,还有一个红色方块来显示添加的新事件的数量。现在我只想知道在不刷新页面的情况下显示新事件的最佳方法是什么。
这是我的代码
| 1 2 3 4 5 6 7 |
<li> <i class=”fa fa-warning fa-2x”> <?php if ( $totalRows_event > 0 ) { ?> <span class=”label label-danger blink”> <?php echo $totalRows_event ?></span> <?php } ?> </li> |
我的PHP查询基本上是事件总数>0的时候,显示一个 <span> 和里面的总数,但是这只在页面刷新或者加载的时候显示。
我正在查看一个类似于下面的 AJAX 请求,它将 PHP 查询结果显示到内部 html 中。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function testAjax ( ) { var result = “” ; $ .ajax ( { url : “data.php” , async : false , success : function (data , textStatus ) { $ ( “#preview” ) .html (data ) ; } , error : function ( ) { alert ( ‘Not OKay’ ) ; } } ) ; return result ; } |
| 1 2 3 4 5 6 |
<li >
<i class = “fa fa-warning fa-2x” > </li > |
但是,每次将新事件添加到我的数据库时,我如何调用该函数而不刷新或加载页面?我认为使用设置的时间间隔或延迟会因为频繁的服务器查询而减慢我的页面,所以我正在寻找其他选项。
- 您可以查看 stackoverflow.com/questions/14112676/ 和 stackoverflow.com/questions/7202978/
php:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public function index ( ) { if ( ! $_GET [ ‘timed’ ] ) exit ( ) ; if ( ! $_GET [ ‘uid’ ] ) exit ( ) ; date_default_timezone_set ( “PRC” ) ; set_time_limit ( 0 ) ; $uid = $_GET [ ‘uid’ ] ; while ( true ) { sleep ( 3 ) ; $lastReadTime = M ( ‘readtime’ ) -> where ( array ( ‘uid’ => $uid ) ) -> field ( ‘lasttime’ ) -> select ( ) ; $result = M ( ‘message’ ) -> where ( array ( ‘send_time’ => array ( ‘gt’ , $lastReadTime ) , ‘touid’ => $uid ) ) -> count ( ) ; if ( $result ) { $data = array ( ‘message’ => $result , ) ; echo json_encode ( $data ) ; exit ( ) ; } else { usleep ( 1000 ) ; exit ( ) ; //return; } } session_write_close ( ) ; } |
js:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
var cometURL = “{:U(GROUP_NAME.’/Comet/index’)}” $ ( function ( ) { ( function longPolling ( ) { //alert(Date.parse(new Date())/1000); $ .ajax ( { url : cometURL , data : { “timed” : Date .parse ( new Date ( ) ) / 1000 , “uid” :$ ( “#uid-hidden” ) .val ( ) } , dataType : “json” , timeout : 5000 , error : function (XMLHttpRequest , textStatus , errorThrown ) { if (textStatus == “timeout” ) { longPolling ( ) ; } else { longPolling ( ) ; } } , success : function (data , textStatus ) { if (data .message != 0 ) { $ (document .body ) .append ( “<i class=’iconfont’style=’position: fixed;top: 28px;right: 30px;color: #2fa8ec;font-size: 20px’>” ) ; $ ( “#messagenum” ) .html ( ‘message(‘ +data .message + ‘)’ ) ; } if (data .image != 0 ) { $ (document .body ) .append ( “<i class=’iconfont’style=’position: fixed;top: 28px;right: 30px;color: #2fa8ec;font-size: 20px’>” ) ; $ ( “#imagenum” ) .html ( ‘New Image(‘ +data .image + ‘)’ ) ; } if (textStatus == “success” ) { longPolling ( ) ; } } } ) ; } ) ( ) ; } ) ; |
我正在使用 THINKPHP 和 Jquery,你可以将其更改为你的方式。(AJAX LONG PULLING)。或者如果你的工作区在 linux 中,你可以使用 swoole 或 workerman 或 websocket 来制作。
声明:本站(华域联盟www.cnhackhy.com)所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)