我试图制作一个联系表格,但我遇到了一些问题:p 我已经读过将 javascript 变量传递给 php 的唯一方法是通过 ajax。我尝试了一些来自 stackoverflow 的建议,但没有任何效果。所以这是我的代码,我想要你的意见。我将如何将 Javascript 变量 (jTemp2) 传递给 php?
示例.html
<!DOCTYPE html>
<html>
<head>
<title> Hello World </title>
</head>
<body>
<?php
// define variables and set to empty values
$fNameErr = "";
$fName = "";
$temp = 0; //flag for mail
$temp2=0; //flag for button
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fName"])) {
$fNameErr = "Required";
$temp=1;
//echo $temp;
} else {
$fName = test_input($_POST["fName"]);
// check if fName only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $fName)) {
$fNameErr = "Invalid";
$temp=1;
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<script>
var jTemp2 = "<?php echo $temp2; ?>";
</script>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="form1" onsubmit="myFunction(jTemp2)">
<fieldset class="fiel">
<legend><b><span class="words">Contact</span></b></legend>
<table border="0">
<tr><td><b><span class="words"> Name: </span></b></td><td><input type="text" size="30" name="fName" id="fName" value="<?php echo $fName;?>"><span class="words"> *</span></td><td><span class="error"> <?php echo $fNameErr;?></span></td></tr>
<tr><td></td><td id="but"><input type="submit" value="Υποβολή" ></td></tr>
<tr><span class="words">* Required</span></tr>
<tr><td><span ><?php echo $temp; echo $temp2; ?></span></td></tr>
</table>
</fieldset>
</form>
<script>
function myFunction(jTemp2)
{
jTemp2++;
}
</script>
</body>
</html>