2013-03-02 189 views
2

我将通过ajax传递一个id以被$ _SESSION删除。 ajax部分工作正常,php在POST中接收id,但是可以放弃的不能被解除。为什么???在这里我的代码:取消设置php会话变量

阿贾克斯部分:

$(".delete").live('click', function(e){ 
    e.preventDefault(); 
    var id_to_remove = $(this).attr('id'); 
    //alert(id_to_remove); 
    $.ajax({ 
     type: "POST", 
     url: 'inc/functions/remove_item_from_cart.php', 
     data: { id : id_to_remove }, 
     success: function(data) { 
      $("#content").load('inc/functions/get_checkout_content.php'); 
      alert(data); 
     } 
    }) 

}); 

PHP的接收部分:

session_start(); 
if(isset($_SESSION['cart']) && isset($_POST['id'])){ 
//echo var_dump($_SESSION['cart']); 
$ncart=$_SESSION['cart']; 
if (count($ncart)>0){ 
    unset($ncart[$_POST['id']]); // this is NOT working!!! 
    $ncart=array_values($ncart); 

    $_SESSION['cart']=$ncart; 
    if(count($ncart)==0){ 
     unset($_SESSION['cart']); 
     unset($_SESSION['cart_total']); 
     echo "all_empty"; 
    } // this if part is the only working! 
} 
} 

任何有益的建议,为什么我不能取消设置会话变量?谢谢!

+2

而正是不使用此代码工作?我们不会猜测发生了什么问题...... – 2013-03-02 19:21:13

+0

您使用的是什么版本的jQuery? ['.live()'](http://api.jquery.com/live/)现已被弃用。 – 2013-03-02 19:21:58

+0

对不起,但只是为了确认,这个过程是否正确:'$ ncart = $ _ SESSION ['cart'];''为'ncart = array_values($ ncart);'为'$ _SESSION ['cart'] = $ ncart ;'? – MichaelRushton 2013-03-02 19:23:52

回答

3

我有我自己的解决方案:

if (count($_SESSION['cart'])>0){ 

foreach ($_SESSION['cart'] as $key => $subarray){ 
    if ($subarray['id'] == $_POST['id']){ 
    unset($_SESSION['cart'][$key]); 
break; 
} 
} 

$_SESSION['cart'] = array_values($_SESSION['cart']); 

} else { 
if(count($_SESSION['cart'])==0){ 
    unset($_SESSION['cart']); 
    unset($_SESSION['cart_total']); 
    echo "all_empty"; 
} 
} 

这是因为数组是这样的:

Array 
(
    [0] => Array 
     (
      [id] => 3 
      [name] => Collier Ano petit 
      [price] => 45 
      [quant] => 1 
      [ptotal] => 45 
     ) 

)