Ajax mysql长轮询

时间:2015-08-30 18:00:30

标签: javascript php jquery mysql ajax

我正在使用mysql进行ajax long轮询功能,但它似乎并没有起作用。我的电脑过热,几分钟后网站崩溃了。此外,poll.php甚至没有从data.php接收内容,相反,poll.php显示{“type”:“connect_error”。

我之前没有做过任何长时间的投票。

我有3个文件:

data.php

<?php

session_start();

define ('DB_HOST', 'localhost');
define ('DB_USER', 'root');
define ('DB_PASSWORD', 'root');
define ('DB_NAME', 'story_creator');

function sqlSelect($query) {

// Create connection
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$result = mysqli_query($conn, $query);

// Check connection
if (mysqli_errno($conn)) {
    echo "Failed: " . mysqli_error($conn);
}

$resultArray = array();

if ($result) { 

    while ($row = mysqli_fetch_array($result)) {
        $resultArray[] = $row;
    }
}

return $resultArray;

}

$news = sqlSelect("SELECT type FROM users_news_feed WHERE user_id =               {$_SESSION['user_id']} AND date > 0;");

echo json_encode($news);

?>

poll.php

<?php

$filename = 'data.php';

$lastmodif = isset($_POST['timestamp'])? $_POST['timestamp']: 0;
$currentmodif = filemtime($filename);

while ($currentmodif <= $lastmodif) {
    usleep(10000);
    clearstatcache();
    $currentmodif = filemtime($filename);
} 

$response = array();
$response['type'] = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);

?>

的Javascript

<script>
    var timestamp = null;

    function waitForMsg(){
    $.ajax({
    type: "POST",
    url: "functions/poll.php",
    async: true,
    cache: false,
    timeout: 50000, /* Timeout in ms */
    data: { 'timestamp': timestamp },
    success: function(data){
    // if(data == ''){
        // Just console.log the data
        console.log(data);
    setInterval(
        waitForMsg(), /* Try again after.. */
        1000); /* milliseconds (15seconds) */
    // }
    },
    complete: function(){
        setInterval(waitForMsg(), 7000);
    }
});
}
$(document).ready(function() {
    waitForMsg();
});
</script>

0 个答案:

没有答案