如果JS会话变量为null,如何避免500内部服务器错误

时间:2015-03-17 12:00:55

标签: javascript php jquery long-polling

我创建了此脚本以从各种Web源读取。此脚本更新所有通知(邮件,帖子,朋友)和他们自己的下拉窗口的详细信息以及两个侧面更新栏。我在我的顶级manu.php页面中使用了这个脚本。

此脚本适用于登录用户。

现在我使用JavaScript var uid = '<? echo $session->id; ?>';传递会话ID变量因此,当用户未登录时,我的浏览器控制台显示500 Internal Server Error,因为此处会话没有ID,因此它传递了uid =''< / p>

我如何克服这个问题?

这是我的JavaScript脚本:

var uid = '<? echo $session->id; ?>';
    function addmailno(type, msg){
    //Do something for display mail/friend/post notification
    }

    function addmailup(type, msg){
    //Do something for display mail/post/friend drop-down.
    }

    function addside(type, msg){
    //Do something for display all friend/new post in side bar.
    }

    function waitFormailno(){
        $.ajax({
            type: "GET",
            url: "serverforupandside.php",
            cache: false,
            async : false,
            dataType : 'json',
            data: "uid="+ uid,
            timeout:15000, 
            success: function(data){ 
                addmailno("MyDivClass", data);
                addmailup("MyDivClass", data);
                addside("MyDivId", data);
                setTimeout(waitFormailno, 15000);
            },
            error: function(){
                setTimeout(waitFormailno, 15000); 
            }
        });
    }

$(document).ready(function(){
    waitFormailno();
});

serverforupandside.php

<?php
include("db.php");
include_once("mysession.php");

while (true) {
if($_GET['uid']){
global $dbh;

//All php query is here one after one

//Output is here by data
$data = array();

$data['upmail'] = $upmail;
$data['upfollow'] = $upfollow;
$data['uppost'] = $uppost;
// etc all

    if (!empty($data)) {
        echo json_encode($data);
        flush();
        mysqli_close($dbh);
    }
    }
    mysqli_close($dbh);
}
?>

1 个答案:

答案 0 :(得分:0)

您的 Javascript代码应修改为:

function waitFormailno(){
        $.ajax({
            type: "GET",
            url: "serverforupandside.php",
            cache: false,
            async : false,
            dataType : 'json',
            data: "uid="+ uid,
            timeout:15000, 
            success: function(data){ 
                addmailno("MyDivClass", data);
                addmailup("MyDivClass", data);
                addside("MyDivId", data);
            }
        });
    }

$(document).ready(function(){
    setInterval(waitFormailno, 15000); // calls a function or evaluates an expression at specified intervals (in milliseconds)
});

PHP代码:

<?php
include("db.php");
include_once("mysession.php");

if (!empty($_GET['uid'])) {
    global $dbh;

    //All php query is here one after one

    //Output is here by data
    $data = array();

    $data['upmail']   = $upmail;
    $data['upfollow'] = $upfollow;
    $data['uppost']   = $uppost;
    // etc all

    if (!empty($data)) {
        echo json_encode($data);
    }


}

此外,您应该在填充$data数组之前添加验证。

相关问题