这是我为 ajax 验证编写的代码。我还没有为表单创建提交按钮。问题是,我必须禁用提交按钮,直到所有字段都填充了适当的信息并以 ajax 方式验证。这只是一个包含两个字段的示例。我有 20 多个这样的字段。请帮我这样做。谢谢你。
形式:
<p>
<label for="cname">Name</label>
<em>*</em><input id="cname" name="name" size="50" minlength="2"onkeyup="checkname()"/>
<span id="target1"></span></p>
<p>
<label for="fat">Father's Name</label>
<em>*</em><input id="cfat" name="father" size="50" onkeyup="checkfather()" />
<span id="target2"></span></p>
Javascript(阿贾克斯):
var ajax = create_ajax_object();
function checkname(){
if(ajax){
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
document.getElementById("target1").innerHTML = ajax.responseText;
}
}
ajax.open("POST", "ajval.php", true);
var values = "name=" + encodeURIComponent(document.commentform.name.value);
values = values + "&action=" + encodeURIComponent("check1");
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.send(values);
}
else{
alert("Your browser doesnt support AJAX!");
}
}
function checkfather(){
if(ajax){
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
document.getElementById("target2").innerHTML = ajax.responseText;
}
}
ajax.open("POST", "ajval.php", true);
var values = "father=" + encodeURIComponent(document.commentform.father.value);
values = values + "&action=" + encodeURIComponent("check2");
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.send(values);
}
else{
alert("Your browser doesnt support AJAX!");
}
}
PHP:
<?php
$action = $_POST["action"];
switch($action)
{
case "check1":
$name=$_POST["name"];
if($name!="")
echo '<img src="green-tick.png" height="20" width="20"/>';
else
echo'<span style="color:red;">Cannot be left blank</span>';
break;
case "check2":
$father=$_POST["father"];
if($father!="")
echo'<img src="green-tick.png" height="20" width="20"/>';
else
echo '<span style="color:red;">Cannot be left blank</span>';
break;
?>