2017-03-05 72 views
0

我有一个Add to Cart按钮。我不知道哪一行我必须将javascript代码放在php代码中

Javacript代码:

echo '<script type="text/javascript">alert("This item is already in the 
cart.");window.location.href="shoppingcart.php";</script>'; 

我想如果该项目已经在购物车中显示的JavaScript代码。 现在,我想问的是我必须把JavaScript放在下面的代码中的哪一行?

下面是HTML代码:

<input type="button" value="Tambah ke Senarai" onclick="addtocart(<?php echo 
$row['no']?>)" /> 

这里是 '添加' 的过程:

if($_REQUEST['command']=='add' && $_REQUEST['productid']>0){ 
    $pid=$_REQUEST['productid']; 
    addtocart($pid,1); 
    header("location:shoppingcart.php"); 
    exit(); 
} 

<script language="javascript"> 
function addtocart(pid){ 
    document.form1.productid.value=pid; 
    document.form1.command.value='add'; 
    document.form1.submit(); 
} 
</script> 

这里是addtocart功能:

function addtocart($pid,$q){ 
    if($pid<1 or $q<1) return; 

    if(is_array($_SESSION['cart'])){ 
     if(product_exists($pid))return; 
     $max=count($_SESSION['cart']); 
     $_SESSION['cart'][$max]['productid']=$pid; 
     $_SESSION['cart'][$max]['qty']=$q; 
    } 
    else{ 
     $_SESSION['cart']=array(); 
     $_SESSION['cart'][0]['productid']=$pid; 
     $_SESSION['cart'][0]['qty']=$q; 
    } 
} 

这里是product_exists功能:

function product_exists($pid){ 
    $pid=intval($pid); 
    $max=count($_SESSION['cart']); 
    $flag=0; 
    for($i=0;$i<$max;$i++){ 
     if($pid==$_SESSION['cart'][$i]['productid']){ 
      $flag=1; 
      break; 
     } 
    } 
    return $flag; 
} 

任何帮助/建议将不胜感激。谢谢。

回答

0

它会去addtocart功能里面,我想:

if(product_exists($pid)){ 
    echo '<script type="text/javascript">alert("This item is already in the cart.");window.location.href="cart.php";</script>'; 
    return; 
} 
+0

它不工作。 javascript不显示。 –

+0

然后你的条件不匹配,试着'退出()'而不是返回 – meda

+0

我只是意识到,我不能添加任何项目后,我改变它使用你的答案,即使我已经使用exit()。 –

相关问题