我正在SilverStripe中建立一个相当简单的网上商店。我正在编写一个函数来从购物车中删除一个项目(在我的例子中是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'
}
}A B的儿子回来了!当我检索到整个购物车时,它仍然同时包含两者。
我怎样才能让order粘住?
发布于 2015-07-16 01:29:22
您的期望是正确的,它应该与您编写的代码一起工作。但是,对于被删除的数据,会话数据的管理方式不能很好地工作,因为它不被看作是状态的改变。只有正在编辑的现有数据才被视为编辑数据。如果您想了解更多信息,请参见Session::递归you ()。我知道的唯一方法是(不幸的)在为'order‘设置新值之前直接强调文本操作$_SESSION
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'));
}https://stackoverflow.com/questions/31443457
复制相似问题