如何在javascript函数中设置php变量?
我想创建一个OTP发送者和检查器。如何在javascript函数中设置php变量?,javascript,php,ajax,one-time-password,Javascript,Php,Ajax,One Time Password,我想创建一个OTP发送者和检查器。 代码如下: 不能使用javascript设置php变量 PHP将在服务器端执行,javascript将在客户端执行。因此,在调用javascript之前,所有PHP代码都已执行 $OTP变量尚未保存。因为代码在服务器端执行,并将被垃圾收集。如果要保存和删除OTP,应使用某种数据库。在编写脚本之前使用php标记,然后再对php变量进行压缩 试试这个 <?php $Mail = "someone@gmail.com"; $OTP = mt_rand
代码如下:
不能使用javascript设置php变量
PHP将在服务器端执行,javascript将在客户端执行。因此,在调用javascript之前,所有PHP代码都已执行
$OTP变量尚未保存。因为代码在服务器端执行,并将被垃圾收集。如果要保存和删除OTP,应使用某种数据库。在编写脚本之前使用php标记,然后再对php变量进行压缩
试试这个
<?php
$Mail = "someone@gmail.com";
$OTP = mt_rand();
$subject = "OTP from HelloBuddy.co.in";
$txt = "You have recieved OTP from HelloBuddy.co.in. The OTP is $OTP. Please enter the OTP in the website. Please note that the OTP will expire in 100 seconds.";
if (mail($Mail,$subject,$txt)){
echo "<p style='color:green; font-size:30px; text-align:center; text-decoration: underline;'>OTP has been successfully sent<br>The OTP will expire in <span id='xpire'>100</span> seconds.<br>Please enter the OTP here:<form method ='POST' action = '' style='text-align:center'><input style='color:green; font-size:30px; text-align:center;text-decoration: underline;'type='number' name ='OTP'><input style='color:white; background-color:#4CAF50;border:2px #4caf50 solid; font-size:30px; cursor:pointer;' type='submit' value='Check'></form></p>";
?><script>
var a = 99;
var x = setInterval(cdown, 1000);
function cdown(){
if (a>=0) {
document.getElementById('xpire').innerHTML = a;
a=a-1;
} else {
clearInterval(x);
clearOTP()
}
function clearOTP{<?=$OTP ='';?>}
</script>
<?
}
?>
Php变量只能在JS中使用,不能操作(初始化/更新)。
上述任务可以通过ajax使用,将otp的值保留在js中并重置,使用ajax执行其他一些操作,如OPT verfication。是否有ajax替代方案我知道这是问题所在。您可以在javascirpt中使用php变量,方法是将其定义为:“”。但我的javscript代码也在Java脚本中。在另一个???@hypermath.com中是否存在OTP?最好的方法是在会话中存储OTP。我想指出,将html/js/php/css混合在一起是一种不好的做法,这会使代码难以阅读、修改,并为难以发现的缺陷创造空间。请研究关注点、MVC框架和模板的分离。谢谢。我已经正确格式化了。你不能详细说明一下,如果邮件()有问题怎么办?像else一样表示{die(ERROR)}。即使到那时,该函数仍将执行?mail()有问题是什么意思?您的邮件函数有错误?如果它有问题,如果您的邮件()有问题,您的IF条件中的脚本将不会执行