使用symfony2和ajax从会话中删除元素

时间:2015-06-22 07:24:20

标签: javascript php jquery ajax symfony

我有一个问题,所以我尝试使用ajax从会话中删除元素。 我的路线是:

shoppingCart_delete:
path: /cartItems/delete/{id}
defaults: { _controller: ShopDesktopBundle:Basket:delete }
requirements:
    id:  \d+
    _method:  POST

我的功能删除:

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

我的ajax代码:

<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>

我的HTML:

<a href="#" onclick="removeItemFromSession({{ product['product_id'] }})" title="Remove this item">Remove</a>

我在控制台中遇到错误:

"NetworkError: 404 Not Found - http://shop.com:1234/cartItems/delete"
你能帮帮我吗? Thx提前!!

1 个答案:

答案 0 :(得分:0)

我想,您需要做以下更改:

1. From path: /cartItems/delete/{id} to path: /cartItems/delete
2. public function deleteAction($id){ to 
 public function deleteAction(Request $request){
  if ($id = $request->request->get('id', false)) {
       ...........
  }
}

简而言之,我们从URL中省略“id”键并通过“Request”访问它。