使用 ajax 从会话中删除项目

Remove an item from session using ajax

我的代码有问题,所以我尝试使用 ajax 请求从会话中删除一个元素。我的 link 在 html 中:

<a style="padding-left:5px;" href="#" onclick="removeItemFromSession({{ product['product_id'] }})" title="Remove this item">Remove</a>

我的 ajax removeItemFromSession() 方法:

 <script type="application/javascript">
    function removeItemFromSession(id){
        console.log(id);
        var id = id,
        url_deploy = "http://"+window.location.hostname+":1234"+"/cartItems/delete";
        console.log(url_deploy);
        $.ajax({
            url: url_deploy,
            type: "POST",
            async: true,
            data: { id:id},
            success: function(data){
                document.location.reload(true);
            },
            error: function(){
            }
        });
    }
</script>

/cartItems/delete的路线:

shoppingCart_delete:
path: /cartItems/delete
defaults: { _controller: ShopDesktopBundle:Basket:delete }
requirements:
    _method:  GET|POST

我在控制器中的删除方法:

 public function deleteAction(){
    $id = $_POST['id'];
    print_r($id);
    $sessionVal = $this->get('session')->get('aBasket');
    unset($sessionVal[$id]);
}

我收到错误:"NetworkError: 500 Internal Server Error - http://shop.com:1234/cartItems/delete"。你能帮我吗 ?提前致谢

在 PHP 中打开错误日志并查看错误日志。错误日志很可能会指出问题所在。如果不是,请从 php 函数中记录 $sessionVal 和 $id 的值;这可能会告诉您问题出在哪里。

第一件事:检查 app/logs/prod.log 是否有任何有意义的错误消息。如果找到 none 检查服务器日志(无论是 Apache 还是其他)。如果不是生产环境,您可能希望在 _dev 模式下 运行 以获得更详细的错误消息。

另一件事:建议避免在`Symfony2 中使用超全局变量 ($_POST,$_SESSION, $_GET,...)。该框架本身提供了获取您需要的所有东西的方法。

例如,您上面的代码应如下所示:

public function deleteAction(){
    # Since you tagged the question with Symfony-2.1
    $id = $this->getRequest()->request->get('id');

    if ( $id ){
        $sessionVal = $this->get('session')->get('aBasket');
        if ( array_key_exists($id, $sessionVal)){
            unset($sessionVal[$id]);
            $sessionVal = $this->get('session')->set('aBasket', $sessionVal);
        }
    }
}

希望这对您有所帮助。