[英]Adding to variable through php won't work
我有一个php脚本,用于为支付系统的信用卡收费,但问题是我有一个带有变量的脚本,每次调用php脚本中的函数时,我都试图将其加1。是它不起作用。 我不确定代码是否有问题,或者是因为加载新页面时未保存变量,因为每次调用php脚本时,它都会重定向到新页面。
带有名为product1.html的变量的html脚本
<script type="text/javascript">
var currentBid = 1;
document.getElementById("currentBid").innerHTML = currentBid;
function addOne() {
currentBid = currentBid +1;
document.getElementById("currentBid").innerHTML = currentBid;
}
</script>
带有名为chargeCard.php的函数的php脚本
<?php
require_once('./stripe-php/init.php');
// Set your secret key: remember to change this to your live secret key in production
// See your keys here https://dashboard.stripe.com/account
\Stripe\Stripe::setApiKey("Removed for safety");
// Get the credit card details submitted by the form
$token = $_POST['stripeToken'];
$myAmount = $_POST['amount'];
$describtion = $_POST['description'];
$myAmount = round((int)$myAmount*100,0);
// Create the charge on Stripe's servers - this will charge the user's card
try {
$charge = \Stripe\Charge::create(array(
"amount" => $myAmount, // amount in cents, again
"currency" => "usd",
"source" => $token,
"description" => $describtion));
echo '<script type="text/javascript">addOne();</script>"';
} catch(\Stripe\Error\Card $e) {
// The card has been declined
}
?>
我试图在php脚本中调用的函数是回显行echo '<script type="text/javascript">addOne();</script>"';
我第一眼看到的是一个语法错误:
您的双引号过多(“)。
可以吗?
正确的回声是:
echo '<script type="text/javascript"> addOne(); </script>';
看来您正在尝试将JavaScript变量从一页转移到另一页。 不幸的是,一旦离开当前页面的范围,JavaScript变量就会消失。
看起来您已经在使用表单将POST发送到服务器,因此,可以维护数据状态的方法是在表单中的服务器和客户端之间来回传递。
例如:
在HTML中,假设您当前的表单结构如下:
<form method="POST" action="/enterYourHandlerUrlHere">
<input type="hidden" name="stripeToken">
<input type="text" name="amount">
<input type="text" name="description">
<!-- This is the important line -->
<input type="hidden" name="currentBid" value="<?php echo $currentBid ?>">
</form>
在您的PHP中,在将以上内容呈现给浏览器之前...
<?php
$currentBid = (isset($_POST['currentBid']) ? $_POST['currentBid'] + 1 : 0);
当您将HTML呈现到屏幕上时,$ currentBid值将被临时存储在页面上的隐藏输入中,可以在客户端上本地访问该值,并且您的后端逻辑以及您只要保持连锁。
另外,可能最好将变量存储在$ _SESSION超全局数组中,如下所示:
if (!isset($_SESSION['currentBid'])) {
$_SESSION['currentBid'] = 0;
} else {
$_SESSION['currentBid']++;
}
这将在多个Web请求中维护您的数据,因为PHP具有这个漂亮的超全局变量来跟踪用户数据。 有关配置和使用$ _SESSION变量的其他信息,请访问以下链接以获取官方文档:
Session解决方案可能需要更多工作,但是绝对值得!
关键概念:
1. php在服务器端运行。 2. javascript在客户端上运行
问题:服务器没有由javascript设置的变量,因为它是在客户端设置的。
方法:您的javascript需要将变量发送到服务器,然后您的php才能使用来自javascript的变量来处理脚本。
方法:使用隐藏形式,并让该形式将变量发送到php脚本。
也许这适合您的情况,但总的来说应该如此。
<form name="hidden" action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<input type="hidden" name="addone" value="<script type=\"text/javascript\">addOne();</script>" />
<input type="submit" value="Submit" />
</form>
和你的PHP代码; 添加此行:
$currentbidget=$_POST['addone'];
您遇到范围问题,除非访问全局,否则无法从功能内更改当前出价
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.