[英]Why don't change $_SESSION variables (PHP) when use AJAX?
我不明白一個簡單的問題。 是否有一個網站需要使用AJAX在頁面上添加貨幣更改(RUR / EUR / USD)。 我認為最好的選擇是-用$_SESSION
所選貨幣編寫,稍后在我的PHP代碼中使用(用於顯示價格等)。
我的index.php
文件:
<?php
session_start();
if (!isset($_SESSION['currency'])) $_SESSION['currency'] = 'rouble';
?>
<!-- Links -->
<a href="#" class="currency__change" data-currency="dollar">Dollar</a>
<a href="#" class="currency__change" data-currency="euro">Euro</a>
<a href="#" class="currency__change" data-currency="rouble">Rouble</a>
<!-- Add jQuery and script -->
<script src="jquery-2.2.4-min.js"></script>
<script src="ajax.js"></script>
這是我的ajax.js
文件:
;(function($, window, document, undefined) {
// On document ready.
$(document).ready(function() {
// Change currency.
$('.currency__change').on('click', function(event) {
// Prevent default.
event.preventDefault();
// Send AJAX request.
$.ajax({
type: 'POST',
url: 'Ajax.php',
data: { 'currency': $(this).data('currency') },
success: function() {
location.reload();
},
error: function() {
alert('Error! Try again later.');
}
});
});
});
})(jQuery, window, document);
現在,我的Ajax.php
文件:
<?php
session_start();
// Change currency.
if ($_POST['currency']) {
unset($_SESSION['currency']);
$_SESSION['currency'] = $_POST['currency'];
}
?>
會話正常啟動,我在服務器上獲取帶有正確標題的會話文件(具有默認值):
但是,如果我單擊AJAX鏈接,則$_SESSION['currency']
變量不會更改。
為什么?
會話保存在服務器上,而不保存在用戶瀏覽器上。 現在,誰是會話保存會話的所有者php在用戶瀏覽器中設置一個名為PHPSESSID的cookie,該cookie具有唯一的ID以標識該特定用戶。 當您調用函數session_start() php時,請使用PHPSESSID為該用戶加載已保存的會話。
要檢查會話是否正常工作,請在設置默認會話后在index.php
添加會話的打印。
<?php
session_start();
if (!isset($_SESSION['currency'])) $_SESSION['currency'] = 'rouble';
?>
<!-- Currency -->
Selected currency: <b><? echo $_SESSION['currency']; ?></b><br>
<!-- Links -->
<a href="#" class="currency__change" data-currency="dollar">Dollar</a>
<a href="#" class="currency__change" data-currency="euro">Euro</a>
<a href="#" class="currency__change" data-currency="rouble">Rouble</a>
<!-- Add jQuery and script -->
<script src="jquery-2.2.4-min.js"></script>
<script src="ajax.js"></script>
如果您需要從javascript訪問貨幣,則可以將其直接存儲在cookie中,或創建一個javascript函數以對返回的ajax調用php,以返回存儲的貨幣。
在這里,您可以找到如何在javascript中存儲和讀取cookie: http : //www.w3schools.com/js/js_cookies.asp
在這里,您可以找到有關php會話的更多信息: http : //php.net/manual/en/intro.session.php
一些建議:您無需取消會話設置,只需覆蓋它即可。 您不能在所有php版本中使用if($_POST['currency'])
,但要確保可以從5.6版開始使用
我懷疑您的變量$(this).data('currency')
沒有設置,並且您的if ($_POST['currency'])
檢查沒有通過。
嘗試僅在for if ($_POST['currency'])
發送一個字符串值以測試該理論。
data: { 'currency': 'Dollar' },
您還可以放入console.log()來查看變量中是否包含任何內容。
console.log("Anything here?",$(this).data('currency'));
附加地
您可以實現一些php錯誤日志記錄,以查看傳入數據的外觀。
<?php
session_start();
// Change currency.
error_log(print_r($_POST,true));
if ($_POST['currency']) {
unset($_SESSION['currency']);
$_SESSION['currency'] = $_POST['currency'];
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.