如果您没有提交表单,则不会执行POST
orGET
方法,并且您在 if 语句中调用来自 POST 的变量$_POST['camp1']
,您将永远不会获得该值。解决此问题的替代方法是使用 JS 或 jQuery,例如:
您修改后的 PHP:
<html>
<head>
<title>Paying process</title>
</head>
<script scr="jquery-1.7.2.js" type="text/javascript" />
<script scr="functions.js" type="text/javascript" />
<body>
<?php
echo ('<form id="payForm" action="https://www.paypal.com/cgi-bin/webscr" method="post">');
echo ('<input type="hidden" name="cmd" value="_cart">');
echo ('<input type="hidden" name="upload" value="1">');
echo ('<input type="hidden" name="business" value="youremail@mail.com">');
echo ('<input type="hidden" name="currency_code" value="US">');
echo ('<input type="checkbox" name="camp1" value="a">');
echo ('<input type="checkbox" name="camp2" value="b">');
echo ('<div id="productInfo" style="display:none;"></div>');
echo ("<input type='submit' value='PayPal'>");
echo ("</form>");
?>
</body>
</html>
函数.js 文件:
$(document).ready(function(){
$("#payForm").submit(function(e){
if($('#productInfo').html() == ''){
//if there is no product in the hidden div, prevent the submit and show msg.
alert('Please select at least one product');
e.preventDefault();
}
});
// event when user clicks a checkbox
$("input[type='checkbox']").on('click', function(){
var checked = $(this).attr('checked');
if(checked){
var value = $(this).val();
$.post('product.php', { value:value }, function(data){
// data = 0 - means that there was an error or no product
if(data != 0){
// At this point you will have your "a" or "b" products in hidden
// Also submit button will appear
// This means that everything was Ok and the user selected a product
$('#productInfo').append(data);
} else {
// data = 0
alert('Please try again.');
}
});
}
});
});
product.php 文件(在 jQuery 帖子中使用):
<?php
if ($_POST && isset($_POST['value'])) {
// db connection
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
// error happened
print(0);
}
mysql_select_db('mydb');
// sanitize the value
$value = mysql_real_escape_string($_POST['value']);
// start the query - I am assuming one :-)
$sql = "SELECT * FROM products WHERE Id = '$value'";
$result = mysql_query($sql, $link);
// check if the product exists
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)){
if($value == 'a'){
echo ("<input type='hidden' name='item_name_1' value='".$row['product_name']."' />");
echo ("<input type='hidden' name='amount_1' value='".$row['product_price']."'>");
} else {
echo ("<input type='hidden' name='item_name_2' value='".$row['product_name']."' />");
echo ("<input type='hidden' name='amount_2' value='".$row['product_price']."'>");
}
}
} else {
// no product found
print(0);
}
?>
现在,只有当用户至少选择一种产品时,您才能提交隐藏值、项目 1 或 2 或两者。
希望这可以帮助 :-)