ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

php – 这是一次真正的长期民意调查吗?

2019-10-03 10:16:42  阅读:228  来源: 互联网

标签:long-polling php jquery mysql


经过大量试验,我成功地能够与数据库保持连续的服务器连接.
现在代码keet cheking并显示消息,如果数据库中有新的.

Plz回顾并告诉
如果此代码中使用了真正的长轮询技术?如果不是,那么PLZ建议,我错了(偏离长轮询)以及如何做出真正的长轮询.

Currenlty,我收到了这些错误.但它仍然保持与数据库的连续连接.

>每次,只拉一条消息而不是全部.(我使用.each循环,但它停止长轮询)
>每10/15秒后,出现令牌错误(Parse erroe(语法错误=意外令牌)).

var last_msg_id = 2;

function load_msgs() {
$.ajax({
type:"Post",
url:"getdata.php",
data:{
    last_msg_id:last_msg_id
},
dataType:"json",
async:true,
cache:false,
success:function(data) {
    var json = data;
    $("#commidwin").append(json['msg']);
    last_msg_id = json["last_msg_id_db"];
    setTimeout("load_msgs()", 1000);
},
error:function(XMLhttprequest, textstatus, errorthrown) {
    alert("error:" + textstatus + "(" + errorthrown + ")");
    setTimeout("load_msgs()", 15000);
}




});
}

Php文件在这里

 $last_msg_id=$_POST['last_msg_id'];
$last_msg_id_db=1;

while($last_msg_id>$last_msg_id_db){
    usleep(10000);
    clearstatcache();

    $sql=mysqli_query($db3->connection,"SELECT * FROM chat_com where id>'$last_msg_id' ORDER by id ASC");

    $sql_m=mysqli_query($db3->connection,"SELECT max(id) as maxid  FROM chat_com");
    $row_m=mysqli_fetch_array($sql_m);
    $last_msg_id_db=$row_m['maxid'];

    while($row=mysqli_fetch_array($sql)){
        $textt=$row['mesg'];

        $last_msg_id_db=$last_msg_id_db;
        $response=array();
        $response['msg']=$textt;
        $response['last_msg_id_db']=$last_msg_id_db;
    }
}

echo json_encode($response);

解决方法:

轮询比简单的更难:只是因为通常输出到浏览器的所有内容都将在完成后进行解释.你的例子很清楚:

success:function(data) {
    var json = data;
    $("#commidwin").append(json['msg']);
    last_msg_id = json["last_msg_id_db"];
    setTimeout("load_msgs()", 1000);
},

jQuery将等到响应完成后构建数据变量,然后调用成功回调.

创建长轮询的一种方法是拥有一个任务和一个跟随者:

>任务是“无限”循环,它只显示捕获和触发事件,放在“框”中.
>跟随者是每隔X秒做一次ajax调用,它查看任务填充的“框”内部,并立即在页面内部进行操作.

这是一个长轮询的例子,没有追随者,只是一个停止民意调查的事件(释放),但你会明白:

<?php

// For this demo
if (file_exists('poll.txt') == false)
{
    file_put_contents('poll.txt', '');
}

// If this variable is set, a long-polling is starting...    
if (isset($_GET['poll']))
{

    // Don't forget to change the default time limit
    set_time_limit(120);

    date_default_timezone_set('Europe/Paris');
    $time = time();

    // We loop until you click on the "release" button...
    $poll = true;
    $number_of_tries = 1;
    while ($poll)
    {
        // Here we simulate a request (last mtime of file could be a creation/update_date field on a base)
        clearstatcache();
        $mtime = filemtime('poll.txt');

        if ($mtime > $time)
        {
            $result = htmlentities(file_get_contents('poll.txt'));
            $poll = false;
        }

        // Of course, else your polling will kill your resources!
        $number_of_tries++;
        sleep(1);
    }

    // Outputs result
    echo "Number of tries : {$number_of_tries}<br/>{$result}";
    die();
}

// Here we catch the release form
if (isset($_GET['release']))
{
    $data = '';
    if (isset($_GET['data']))
    {
        $data = $_GET['data'];
    }
    file_put_contents('poll.txt', $data);
    die();
}
?>

<!-- click this button to begin long-polling -->
<input id="poll" type="button" value="Click me to start polling" />

<br/><br/>

Give me some text here :
<br/>
<input id="data" type="text" />
<br/>

<!-- click this button to release long-polling -->
<input id="release" type="button" value="Click me to release polling" disabled="disabled" />

<br/><br/>

Result after releasing polling :
<div id="result"></div>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">

    // Script to launch polling
    $('#poll').click(function() {
        $('#poll').attr('disabled', 'disabled');
        $('#release').removeAttr('disabled');
        $.ajax({
            url: 'poll.php',
            data: {
                poll: 'yes' // sets our $_GET['poll']
            },
            success: function(data) {
                $('#result').html(data);
                $('#poll').removeAttr('disabled');
                $('#release').attr('disabled', 'disabled');
            }
        });
    });

    // Script to release polling
    $('#release').click(function() {
        $.ajax({
            url: 'poll.php',
            data: {
                release: 'yes', // sets our $_GET['release']
                data: $('#data').val() // sets our $_GET['data']
            }
        });
    });

</script>

示范:here.

标签:long-polling,php,jquery,mysql
来源: https://codeday.me/bug/20191003/1848495.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有