从Jquery获取PHP $ _SESSION变量?

kha*_*rim 1 javascript php session jquery

我还不是JSON/AJAX大师,所以我不知道该怎么做.

我需要一个$ _SESSION ['name'] PHP变量来处理我的jQuery内容,我不知道如何访问它...考虑:

// the 'who is typing' shindig
    $.ajax(
    {
        url: "whos_typing.html",
        cache: false,
        success: function(whos)
        {   
                // here I need to access $_SESSION['name'] and do stuff with it

            $("#soandso").html(whos); //Insert who's typing into the #soandso       
        }
        });
Run Code Online (Sandbox Code Playgroud)

Mak*_*ita 11

你需要注入它,像这样:

var sessName = '<?php echo $_SESSION['name']?>';
Run Code Online (Sandbox Code Playgroud)

包含此脚本的文件必须由php解释器执行(即.php文件)

编辑:承认Radu的观点,对于未经过数据处理的数据,执行会更安全:

var sessName = <?php echo json_encode($_SESSION['name']) ?>;
Run Code Online (Sandbox Code Playgroud)

  • 确保*always*[`json_encode()`](http://php.net/json_encode)*any*将转换为JavaScript代码的值,否则你将自己打开[跨站点脚本]( http://en.wikipedia.org/wiki/Cross-site_scripting). (5认同)