doulei1965 2014-03-08 14:25
浏览 68
已采纳

我应该通过ajax函数传递会话变量还是直接在脚本中访问它?

I have a page that uses an ajax function to get updates from another page.The function uses the user's id, which is retrieved from a session variable to find any updates, which is then displayed in a "Updates" div. While my script is working currently, i find myself wondering if i could retrieve the userid stored in the session variable in my Ajax page instead of passing the userid through the ajax function. Are there any advantages and/or disadvantages to passing the userid through the ajax function instead of accessing it directly in the ajax script?

My Ajax function:

function FetchUpdate()
{
    var userid= <?php echo $_SESSION['UserID'] ?>;
    $.ajax(
    {
        type:"POST",
        url:"getupdates.php",
        data:{userid:userid}
    })

    .done(function(data){
        $("#Updates").html(data);
        setTimeout(FetchUpdate,1000*60);

    })

}

Ajax page(getupdates.php)

session_start();
$userid=$_SESSION['UserID'];
//fetches updates
//echos updates
  • 写回答

4条回答 默认 最新

  • doumu1212 2014-03-08 14:54
    关注

    This is an example approach of your situation:

    Javascript :

    function fetchUpdate(){
        var data = {}
            data.command = 'getUpdate'
        $.post('getupdates.php', data, function(result){
            var r = JSON.parse(result)
            try {
                if(r.status == true){
                    console.log('Success! '+r.message)
                }else{
                    console.log(r.message)
                }
            }catch(e){
                console.log(result)
            }
        })
    }
    

    PHP :

    <?php
    if(!isset($_SESSION)){$session = new Session();}
    $uid = isset($_SESSION['userID']) ? $_SESSION['userID'] : 0;
    
    if(isset($_POST['command'])){$cmd = $_POST['command']}
    
    switch($cmd){
        case 'getUpdate':
        // Check $uid with database here.
            if($uid > 0){
                $response['status'] = true;
                $response['message'] = 'User details have been updated.';
            }else{
                $response['status'] = false
                $response['message'] = 'Invalid user.'
            }
        break;
        // Process other commands here.
    }
    // Return output
    echo json_encode($response);
    
    ?>
    

    Hope this helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题