2017-03-05 73 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()。 –

相關問題