Ajax技术

来源:互联网 发布:建筑电气常用数据 编辑:程序博客网 时间:2024/06/07 15:58

解决方案:在登录提交时,浏览器界面不刷新,提交改为在后台异步运行,当服务器端验证完毕,将结果在界面上原来登录表单所在的位置显示出来。

Ajax核心代码:

<script language="JavaScript">function showInfo(){var xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");xmlHttp.open("get","info.jsp",true);xmlHttp.onreadystatechange = function(){if(xmlHttp.readyState==4){infoDiv.innerHTML = xmlHttp.responseText;}}xmlHttp.send();}</script>
API解释:

Msxml2.XMLHTTP是IE浏览器内置的对象,该对象具有异步提交数据和获取结果的功能,如果不是IE浏览器,则实列化方法如下:

<script language="JavaScript">var xmlHttp = new XMLHttpRequest();</script>//Mozilla等浏览器
指定异步提交的目标和方式,调用了xmlHttp的open方法。

xmlHttp.open("get","info.jsp",true);

也可以提交参数到目标info.jsp

xmlHttp.open("get","info.jsp?account=0001",true);

info.jsp可以通过request.getParameter("account");获取account的值。

参数true,为true表示异步请求,false为非异步请求。

该代码中用到xmlHttp的onreadystatechange事件,表示xmlHttp状态改变时,调用处理代码。

在请求的过程中,xmlHttp的状态不断改变,其状态保存在xmlHttp的readyState属性中,用xmlHttp,readyState表示。

源码演示:

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>LOGIN</title></head><body><script language="JavaScript">function login() {var account = document.loginForm.account.value;var password = document.loginForm.password.value;var xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");var url = "LoginServlet?account="+account+"&password="+password;xmlHttp.open("post",url,true);xmlHttp.onreadystatechange=function(){if(xmlHttp.readyState==4){resultDiv.innerHTML = xmlHttp.responseText;//resultDiv即为表单上的div名称}else{resultDiv.innerHTML += "正在登录,请稍后.....";}}xmlHttp.send();}</script>欢迎登陆学生管理系统<hr><div id="resultDiv"><form name="loginForm">请您输入账号:<input type="text" name="account"/><br/>请您输入密码:<input type="password" name="password"/><br/> <input type="button" value="登录" onclick="login()"/></form></div></body></html>
loginFail.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body>登录失败!</body></html>
loginsuccess.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body>欢迎${account}登录成功!<br/></body></html>






0 0
原创粉丝点击