Session 在SilverStripe中取消设置会话
我正在SilverStripe建立一个非常简单的在线商店。我正在编写一个函数来从购物车中删除一个项目(Session 在SilverStripe中取消设置会话,session,silverstripe,Session,Silverstripe,我正在SilverStripe建立一个非常简单的在线商店。我正在编写一个函数来从购物车中删除一个项目(order) 我的设置: 我的端点将JSON返回到视图中,以便在ajax中使用 public function remove() { // Get existing order from SESSION $sessionOrder = Session::get('order'); // Get the product id from POST $product
order
)
我的设置:
我的端点将JSON返回到视图中,以便在ajax中使用
public function remove() {
// Get existing order from SESSION
$sessionOrder = Session::get('order');
// Get the product id from POST
$productId = $_POST['product'];
// Remove the product from order object
unset($sessionOrder[$productId]);
// Set the order session value to the updated order
Session::set('order', $sessionOrder);
// Save the session (don't think this is needed, but thought I would try)
Session::save();
// Return object to view
return json_encode(Session::get('order'));
}
我的问题:
当我将数据发布到此路由时,产品将被删除,但只是暂时删除,然后下次调用remove时,上一项将返回
示例:
订单对象:
{
product-1: {
name: 'Product One'
},
product-2: {
name: 'Product Two'
}
}
当我发布以删除product-1
时,我得到以下信息:
{
product-2: {
name: 'Product Two'
}
}
这似乎起到了作用,但我尝试用删除product-2
,并得到以下结果:
{
product-1: {
name: 'Product One'
}
}
B的儿子回来了!当我检索整个购物车时,它仍然包含这两个部分
如何使
订单
保持不变 您的期望是正确的,它应该与您编写的代码配合使用。但是,会话数据的管理方式在删除数据时不起作用,因为它不被视为状态的更改。只有正在编辑的现有数据才会被视为这样。如果您想了解更多信息,请参阅Session::recursivelyApply()。
我知道的唯一方法是(不幸的是)在设置“order”的新值之前直接操作$\u会话
public function remove() {
// Get existing order from SESSION
$sessionOrder = Session::get('order');
// Get the product id from POST
$productId = $_POST['product'];
// Remove the product from order object
unset($sessionOrder[$productId]);
if (isset($_SESSION['order'])){
unset($_SESSION['order']);
}
// Set the order session value to the updated order
Session::set('order', $sessionOrder);
// Return object to view
return json_encode(Session::get('order'));
}
啊,混蛋!我想可能是这样的,似乎有点疏忽。。。我可能会尝试一个未设置方法的拉取请求。不管怎么说,这项工作现在非常出色。