通过javascript将值传递到php


Passing values through javascript to php

我正在创建一个小型购物车程序,我使用以下代码来输入值。

<input type="button" value="Add to Cart : <?php echo $row['PART_NO']; ?>" onclick="addtocart('<?php echo $item; ?>')" /> 

值通过以下javascript代码。

function addtocart(pid){
    alert(pid);
    document.form1.productid.value=pid;
    document.form1.command.value='add';
    document.form1.submit();
}
<body>
<form name="form1">
<input type="hidden" name="productid" />
<input type="hidden" name="command" />
</form>
<?php
if ( isset($_REQUEST['command']) && $_REQUEST['command'] == 'add' &&    $_REQUEST['productid']>0 ){
    $pid=$_REQUEST['productid'];
    addtocart($pid,1);
    header("location:shoppingcart.php");
    exit();
}
?>

当我像02190249那样插入productid时,它会经过javascript代码和php代码并加载shoppingcart.php。但像PF161202这样插入productid不会加载shoppingcart.php。如何通过js将PF161202之类的值传递给php代码。

从php代码中删除$_REQUEST['productid']>0。它只检查大于0numbers(02190249),但根据您的问题,您正在通过string(PF161202)。

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