我试图联系表格,但我有一些问题:p 我已经读过将javascript变量传递给php的唯一方法是通过ajax。我已尝试过stackoverflow的一些建议,但没有任何效果。所以这是我的代码,我想要你的意见。 我将如何将Javascript变量(jTemp2)传递给php?
sample.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>
答案 0 :(得分:1)
在<form> ... </form>
<script type="text/javascript">
document.write('<input type="hidden" name="jTemp2" value="'+ jTemp2 +'">');
</script>
现在,当表单发布到PHP脚本时,变量的值将位于:
<?php
$jTemp2 = isset($_POST['jTemp2']) ? $_POST['jTemp2'] : '';
?>