我将 Ajax 与 PHP 一起用于 HTML 表单。这是我的 HTML 表单。
<form id="form1" name="form1" method="post" action="">
Student Category :
<input type="radio" name="category" value="Full Time" onclick='showUser(this.value)'/>Full Time</br>
<input type="radio" name="category" value="Part Time" onclick='showUser(this.value)'/>Part Time</br>
Index Number :<div id="txtHint"></div><br/>
<button type="submit" name="save" id="save" class="btn">SUBMIT</button></form>
我将 Ajax 与学生类别和索引号一起使用。如果用户选择第一个单选按钮,索引号中将显示一个默认值为“MPhil/FT/2013/”的文本框。如果选择第二个单选按钮,默认值为“MPhil/PT/2013/”。
这是我的 Ajax 和 JS 代码:
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getUser.php?q="+str,true);
xmlhttp.send();
}
</script>
getUser.php 文件包含以下代码。
<?php
$q = $_GET['q'];
$r = date("Y");
if ($q == 'Full Time') {
echo "<input type='text' name='reg' class='form-control' value='M.Phil/FT/$r/' />";
} else if ($q == 'Part Time') {
echo "<input type='text' name='reg' class='form-control' value='M.Phil/PT/$r/' />";
}
?>
获取表单值的代码(包含在html表单的同一页中)
<?php
if (isset($_POST['save'])) {
if (isset($_POST['category'])) {
$d=($_POST['category']);
}
if (isset($_POST['reg'])) {
$a=$_POST['reg'];
echo $a;
}
}
虽然输入框 'reg' 有一个值,但提交时不会打印表单 $a。也就是说,它是(!isset($_POST['reg']))
。我想得到我的输入框值。但据说是!isset。有人可以帮我吗?PS- 除第三个代码外,以上显示的所有代码都在一个文件中。第三个代码在 getUser.php 文件中。谢谢你。