从Jquery获取PHP $ _SESSION变量?

我还不是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 } }); 

你需要注入它,像这样:

 var sessName = ''; 

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

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

 var sessName = ; 

您需要使用$.post从服务器检索变量。 你会有这样的事情:

  $.post('echoMyVar.php', {post: 1}, function(data){ myVar = data['myVar']; }); 

这是非常基本的,首先需要检查data是否为空。 在echoMyVar.php中,您只需要基本上需要以下内容:

  header('Content: application/json', 1); $returnVal = array('myVar', $_SESSION['myVar']); echo json_encode($returnVal); 

同样,这是一个shell,不安全,不会处理任何错误。

 var name= "" 

会做的 。 。 。

记住 php是一个服务器端脚本。 。 .so优先并先执行并将html吐出到客户端(Jquery,javacript),它将在您的浏览器中执行。 。 。 。

因此,您可以使用服务器端变量与客户端共享。 。 。 但不是相反。 。 。

最简单的方法可能是将您的javascript代码包含在.php文件中。 然后你可以简单地做:

 var phpVar =  

类似的post

whos_typing.php中的服务器端:

 'Bob', 'session'=>$_SESSION, // Be sure that you're not storing any sensitive data in $_SESSION. // Better is to create an array with the data you need on client side: // 'session'=>array('user_id'=>$_SESSION['user_id'], /*etc.*/), )); exit(0); 

客户端:

 // the 'who is typing' shindig $.ajax({ url: "whos_typing.php", dataType: 'json', cache: false, success: function(data) { var session = data.session, who = data.who; console.log(session.user_id); // deal with session $("#soandso").html(who); //Insert who's typing into the #soandso } }); 

将它发送到浏览器时,需要从PHP echo显会话变量。 我假设whos_typing.html只是PHP脚本的URL。