AJAX学习笔记之 制作自动校验的表单

多数注册页面,在注册时都需判断用户名是否存在,下面以该实例,实现异步判断:

9-9.html:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>自动校验的表单</title>
<style type="text/css">
<!--
form{
 padding:0px; margin:0px;
 font-size:12px;
 font-family:Arial, Helvetica, sans-serif;
}
input{
 border:1px solid #004082;
 font-size:12px;
 font-family:Arial, Helvetica, sans-serif;
}
-->
</style>
<script language="javascript">
var xmlHttp;
function createXMLHttpRequest(){
 if(window.ActiveXObject)
  xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
 else if(window.XMLHttpRequest)
  xmlHttp = new XMLHttpRequest();
}
function showResult(sText){
 var oSpan = document.getElementById("UserResult");
 oSpan.innerHTML = sText;
 if(sText.indexOf("already exists") >= 0)
  //如果用户名已被占用
  oSpan.style.color = "red";
 else
  oSpan.style.color = "black";
}
function startCheck(oInput){
 //首先判断是否有输入,没有输入直接返回,并提示
 if(!oInput.value){
  oInput.focus();  //聚焦到用户名的输入框
  document.getElementById("UserResult").innerHTML = "User cannot be empty.";
  return;
 }
 //创建异步请求
 createXMLHttpRequest();
 var sUrl = "9-9.aspx?user=" + oInput.value.toLowerCase() + "&timestamp=" + new Date().getTime();
 xmlHttp.open("GET",sUrl,true);
 xmlHttp.onreadystatechange = function(){
  if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
   showResult(xmlHttp.responseText); //显示服务器结果
 }
 xmlHttp.send(null);
}
</script>
</head>
<body>
<form name="register">
<table cellpadding="5" cellspacing="0" border="0">
 <tr><td>用户名:</td><td><input type="text" οnblur="startCheck(this)" name="User"></td> <td><span id="UserResult"></span></td> </tr>
 <tr><td>输入密码:</td><td><input type="password" name="passwd1"></td> <td></td> </tr>
    <tr><td>确认密码:</td><td><input type="password" name="passwd2"></td> <td></td> </tr>
 <tr>
  <td colspan="2" align="center">
  <input type="submit" value="注册">
        <input type="reset" value="重置">
  </td> <td></td>
 </tr>
</table>
</form>
</body>
</html>

 

9-9.aspx:

 

<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="gb2312" %>
<%@ Import Namespace="System.Data" %>
<%
 Response.CacheControl = "no-cache";
 Response.AddHeader("Pragma","no-cache");
 
 if(Request["user"]=="isaac")
  Response.Write("Sorry, " + Request["user"] + " already exists.");
 else
  Response.Write(Request["user"]+" is ok.");

%>

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值