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 Pwm双极模式H桥驱动控制电机
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题