XMLHttpRequest、prototype实现ajax

 

注释很详细,不用单独说明。

 

其中index.jsp文件为:

<%@ page language="java" contentType="text/html;charset=UTF-8"%>
<html>
<head>
    <title>xmlhttprequest ajax demo</title>
    <script src="prototype-1.6.0.2.js"></script>
    <script type ="text/javascript" language ="javascript" >
        var req; //定义变量,用来创建xmlhttprequest对象
        function creatReq() // 创建xmlhttprequest,ajax开始
        {
         var username=document.getElementById("form1").username.value;
            var url="check.jsp?user="+username; //要请求的服务端地址
            //XMLHttpRequest实现ajax
            if(window.XMLHttpRequest) //非IE浏览器,用xmlhttprequest对象创建
            {
                req=new XMLHttpRequest();
            }
            else if(window.ActiveXObject) //IE浏览器用activexobject对象创建
            {
                req=new ActiveXObject("Microsoft.XMLHttp");
            }
           
            if(req) //成功创建xmlhttprequest
            {
                req.open("GET",url,true); //与服务端建立连接(请求方式post或get,地址,true表示异步)
                req.onreadystatechange = callback; //指定回调函数
                req.send(null); //发送请求
            }
           
           
            //prototype实现ajax
          /*var myAjax = new Ajax.Request(
         url,
         {
         method: 'get',
         //parameters:"user="+username,
          onComplete: callback
          });*/
           
        }
        //用prototype时,函数必须传一个参数,如:function callback(req)
        function callback() //回调函数,对服务端的响应处理,监视response状态
        {
            if(req.readyState==4) //请求状态为4表示成功
            {
                if(req.status==200) //http状态200表示OK
                {
                    document.getElementById ("myTime").innerHTML =req.responseText;//所有状态成功,执行此函数,显示数据
                }
                else //http返回状态失败
                {
                    alert("服务端返回状态" + req.statusText);
                }
            }
        }
    </script>
</head>
<body>
 <form id="form1" action="" >
     用户名:<input id="username" name="username" type="text" οnblur="creatReq()"/><div id="myTime" style="display:inline"></div><br>
     密码:<input id="password" name="password" type="text" />
     <input type="submit" value="submit">
    </form>
</body>
</html> 

 

 

check.jsp文件为:

<%@ page contentType="text/html;charset=utf-8"%>
<%
String username = request.getParameter("user");
if(username==null||username=="")
 out.print("不能为空");
else{
 if("xin".equals(username))
  out.print("用户名已经被注册");
 else
  out.print("用户名尚未被使用");
}  
%>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值