我正在创建一个票务预订申请表。我正在尝试使用PHP和Ajax创建一个基本的购物车,当我点击添加到购物车按钮时,它使用Ajax将座位号发送到“seatchecker.php”文件,该文件检查座位是否可用,然后如果是可用,它使用Ajax将该座位号发送到“seatadder.php”文件,该文件应将座位号添加到Session阵列。但每次我点击“添加到购物车”它只显示新值,而不是显示整个购物车。可能是每次都覆盖会话变量?任何帮助,将不胜感激。感谢
<?php
session_start();
// Getting the value sent by checkseats.php using ajax
$seat_added = $_GET['seatadd'];
// ARRAY OF SESSION VARIABLE
$_SESSION['seat_add'] = array();
function multiple_seats_adder($getseat){
array_push($_SESSION['seat_add'],$getseat);
// TESTING
print_r($_SESSION['seat_add']);
// TESTING
echo sizeof($_SESSION['seat_add']);
}
echo multiple_seats_adder($seat_added);
?>
答案 0 :(得分:1)
问题似乎源于每次调用脚本时正在初始化空数组的seat_add
键的事实。最有可能的是,这不是你想要的。请考虑以下代码:
<?php
session_start();
// Getting the value sent by checkseats.php using ajax
$seat_added = $_GET['seatadd'];
// ONLY INITIALIZE THIS TO AN EMPTY ARRAY IF IT DOESN'T EXIST AT ALL:
if(!isset($_SESSION['seat_add'])){
// ARRAY OF SESSION VARIABLE
$_SESSION['seat_add'] = array();
}
function multiple_seats_adder($getseat){
array_push($_SESSION['seat_add'], $getseat);
// TESTING
print_r($_SESSION['seat_add']);
// TESTING
echo sizeof($_SESSION['seat_add']);
}
multiple_seats_adder($seat_added);