该页面是网上商店页面,用户得到js提示输入自己的购物车名称,然后选择一个产品添加到购物车,注意每个产品都有自己的表单和添加到购物车按钮,问题是我希望购物车的名称是静态的。一旦用户输入它,它就会被存储以用于他选择的所有下一个产品,但现在发生的情况是添加第一个产品工作正常,但对于第二个产品,购物车的名称似乎为空。
JS代码:
function myFunction() {
var person = prompt("Please enter Cart Name");
document.getElementById("person").value=person;
document.getElementById("form").submit();
// if (person != null) {
// document.getElementById("demo").innerHTML =
// "Your Cart Name is " + person;
//}
}
PHP:
<?php
//ini_set('display_errors',1);
// error_reporting(E_ALL);
include('connection.php');
if ( isset($_POST['Pro_ID'], $_POST['Price'] , $_POST['Pro_Name'] ) ) {
static $cart=$_POST['cart_Name']; //this line is just a try, but it gives me an error: Parse error: syntax error, unexpected '$_POST' (T_VARIABLE)
$qry="INSERT INTO shopping_cart(Cart_Name,Pro_Name,Pro_ID,Price) VALUES ('$cart','".$_POST['Pro_Name']."',".$_POST['Pro_ID'].",".$_POST['Price'].")";
$result = mysql_query ($qry );
$qry = 'SELECT * FROM product' ;
}
else
$qry = 'SELECT * FROM product' ;
//Run QUERY
$result = mysql_query ($qry);
?>
对于变量 cart_Name,它已作为隐藏输入传递
基本上你会做这样的事情:
if(!isset($_SESSION['cart_name']) && isset($_POST['cart_name'])) {
$_SESSION['cart_name'] = $_POST['cart_name'];
}
// then reference $_SESSION['cart_name'] from there on out.
在尝试与
session_start()
互动之前,请不要忘记在您的页面上拨打 $_SESSION
。
现在在 JS 端,您只想在购物车尚未命名时调用提示。所以我要做的就是在页面上的某个地方输出一个 var - 需要在调用页面上的
myFunction()
之前输出。我可能会把它放在顶部附近:
<script type="text/javascript">
var cartName = <?php echo isset($_SESSION['cart_name'])
? json_encode($_SESSION['cart_name'])
: 'null';
?>;
</script>
然后在你的函数中你可以检查它:
function myFunction() {
// note the lack of `var` - this means we are referencing the global namedCart
// normally I would recommend passing this in as an argument but I don't have enough detail
// on your set up
if (namedCart === null) {
// if named cart doesn't exist we name it from the prompt
namedCart = prompt("Please enter Cart Name");
}
document.getElementById("person").value=namedCart;
document.getElementById("form").submit();
}