-3

我试图制作一个联系表格,但我遇到了一些问题: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>
4

1 回答 1

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'] : '';

?>
于 2013-10-17T13:19:09.977 回答