问题描述
在 PHP/HTML 页面内,我试图在 php 中启动一个会话,然后将一个值设置为一个会话变量,我正在一个 Javascript 函数中尝试它,在这个函数有一个 if 语句,但是当我立即转到页面时,if 语句中的 php 代码会自动运行,当我希望代码仅在用户接受条款时运行...
Inside a PHP/HTML page i'm trying to start a session in php and then set a value to a session variable, and i'm trying that inside a Javascript function, and in this function there is a if statement, but the php code inside the if statement runs automatically when i go to the page immediately, when i want the code to run only when the user accept the terms...
这是我的代码:
HTML:
<label>
<input type="checkbox" name="terms" id="terms-checkbox">
<font color="#090909" size="+1">I agree to the Terms and Conditions.</font>
</label>
Javascript:
if(document.getElementById("terms-checkbox").checked){
<?php session_start(); $_SESSION["ITA"] = "Yes"; ?>
window.open('DL.php?App=STOPit');
}
因此,当我打开包含先前 Javascript 代码的 php 页面时,即使条件尚未满足,$_SESSION["ITA"] 变量也将等于是".
So when i open the php page that contains that previous Javascript code, the $_SESSION["ITA"] variable will be equals to "Yes" even that the condition is not met yet.
希望有人能帮助我.
推荐答案
为了更好地理解 php
在服务器端运行,javascript
在客户端运行.
For your better understanding php
runs on the server side and javascript
runs on the client side.
如果您使用 form
提交数据,或者您必须使用 javascript
进行 ajax
调用,那么您正在尝试做的事情是可能的.
What you are trying to do is possible if you submit the data using a form
or you have to make an ajax
call using javascript
.
下面是做类似事情的一种方法.
Below is one way of doing something similar.
<?php
session_start();
if(isset($_POST['terms'])) {
$_SESSION["ITA"] = "Yes";
header('Location: DL.php?App=STOPit');
}
?>
<form action="<?php $_SERVER["PHP_SELF"] ?>" method="post">
<label>
<input type="checkbox" name="terms" id="terms-checkbox">
<font color="#090909" size="+1">I agree to the Terms and Conditions.</font>
<input type="submit" value="Submit">
</label>
</form>
这篇关于PHP 代码在不需要时自动在 Javascript 中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!