[英]JavaScript with php variabe isn't working
I'm new to to working with php html and javascript so I apologize if this question is bad but whenever I add this variable that echos php I can no longer advance the program to the next window. 我是新手使用php html和javascript,所以我很抱歉,如果这个问题很糟糕,但每当我添加这个变量,echos php我不能再将程序推进到下一个窗口。 The only thing I can think of is that the next window is a html and not a php file.
我唯一能想到的是下一个窗口是一个html而不是一个php文件。 Would that be the reason or am I doing something else wrong?
这是原因还是我做错了什么? Thanks!
谢谢!
<script>
var winner = <?php echo $winnerName ?>;
//Creates random num for winner base on num of members.
function changeNum() {
//Num of members.
num = document.getElementById("num").value;
//winner.
num2 = Math.round((Math.random() * (num - 1) + 1));
//Storage to second page
localStorage.setItem("winner", num2);
localStorage.setItem("name", winner);
window.location = "second_page.html";
}
</script>
PHP will print out your string in plain text and to the browser it will exactly like if you were to have typed and hardcoded the string held by $winnerName
in the file itself. PHP将以纯文本形式打印出您的字符串,如果你要在文件本身中输入
$winnerName
保存的字符串,那么它将完全$winnerName
。
For example if $winnerName = 'Bob'
the browser will see var winner = Bob;
例如,如果
$winnerName = 'Bob'
,浏览器将看到var winner = Bob;
and complain that you haven't defined the variable Bob
. 并抱怨你没有定义变量
Bob
。
Keeping that in mind, there are two methods to make javascript treat your string as a string, and not a variable. 记住这一点,有两种方法可以使javascript将字符串视为字符串,而不是变量。
var winner = <?php print json_decode($winnerName); ?>;
var winner = '<?php print $winnerName; ?>'
Both of which will display to the browser var winner = 'Bob'
. 两者都将显示给浏览器
var winner = 'Bob'
。
A couple of potential issues: 一些潜在的问题:
$winnerName
is probably a string, which means that you need to wrap it in quotes: '<?=$winnerName;?>'
(and probably escape it as well to be on the safe side): '<?=addslashes($winnerName);?>'
$winnerName
可能是一个字符串,这意味着你需要将它包装在引号中: '<?=$winnerName;?>'
(并且可能为了安全起见而将其转义): '<?=addslashes($winnerName);?>'
Make sure that num
is a legitimate integer: parseInt(document.getElementById("num").value)
just in case that might be throwing an error. 确保
num
是一个合法的整数: parseInt(document.getElementById("num").value)
以防万一可能引发错误。
Also, you'll want to look at your console to see what javascript error is being throw - it will narrow down the issue for you. 此外,您将需要查看您的控制台以查看正在抛出的javascript错误 - 它将为您缩小问题范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.