[英]Get a PHP $_SESSION variable from 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
}
});
您需要注入它,如下所示:
var sessName = '<?php echo $_SESSION['name']?>';
包含此腳本的文件必須由php解釋器執行(即.php文件)
編輯:根據Radu的觀點,對於未消毒的數據執行起來會更安全:
var sessName = <?php echo json_encode($_SESSION['name']) ?>;
您需要使用$.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);
同樣,這是一個外殼,不安全,不會處理任何錯誤。
var name= "<?php echo $_SESSION['user_name'];?>"
會做的 。 。 。
請記住, php是服務器端腳本。 。 .so優先,並首先執行,然后將html吐給客戶端(Jquery,javacript),該客戶端將在您的瀏覽器中執行。 。 。 。
因此,您可以使用服務器端變量與client共享。 。 。 但並非相反。 。 。
最簡單的方法可能是將您的JavaScript代碼包含在.php文件中。 然后,您可以簡單地執行以下操作:
var phpVar = <?php echo $_SESSION['name']; ?>
在whos_typing.php中的服務器端:
<?php
//...
header('Content-Type: application/json');
echo json_encode(array(
'who'=>'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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.