通过javascript将值传递给php

时间:2016-05-14 17:45:55

标签: javascript 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();
}

?>

当我插入像{strong> productid 这样的02190249时,它会通过javascript代码和php代码并加载shoppingcart.php。但是插入productid,例如 PF161202 ,它不会加载shoppingcart.php。如何通过js将 PF161202 等值传递给php代码。

1 个答案:

答案 0 :(得分:1)

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

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