【问题标题】:Unset session in SilverStripe在 SilverStripe 中取消设置会话
【发布时间】:2015-10-05 06:20:39
【问题描述】:

我正在 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 保持不变?

【问题讨论】:

    标签: session silverstripe


    【解决方案1】:

    您的期望是正确的,它应该适用于您编写的代码。但是,会话数据的管理方式不适用于删除数据,因为它不被视为状态更改。只有正在编辑的现有数据才会被视为这样。如果您想了解更多信息,请参阅 Session::recursivelyApply()。 我知道的唯一方法是(不幸的是)在为“订单”设置新值之前直接强调 textmanipulate $_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'));
    }
    

    【讨论】:

    • 啊混蛋!我认为可能是这种情况,似乎有点疏忽......我可能会对未设置方法的拉取请求进行尝试。无论如何,现在效果很好。
    猜你喜欢
    • 2017-01-06
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 2016-10-01
    • 2013-02-17
    相关资源
    最近更新 更多