前提:什么是Ajax?
AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
Ajax的本质:
和刷新页面一样都是向服务器发送了一个http请求获得结果并进行显示(超链接或者提交表单),但不同的是ajax不需要刷新整个界面,只需要实现浏览器提供的接口创建一个XMLHttpRequest对象,使用现有标准的新方法即可实现向服务器发送http请求!使用Ajax只需要理清楚以下几点:
- 请求url(服务器端路径)
- 请求方法:get or post
- 请求数据(请求数据格式、数据是自定义还是通过JS界面获取)
- 响应数据返回(响应数据格式、如何接收并解析数据)
- 响应数据的显示(通过JS在html界面哪里显示)
1.入门程序:用户名校验
- 浏览器端: register.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=ISO-8859-1">
<title>Insert title here</title>
</head>
<script>
function ajaxFunction(){
var xmlHttp;
try{ // Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e){
try{// Internet Explorer
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
return xmlHttp;
}
function showHint(str)
{
//1.创建xmlhttprequest对象
var request = ajaxFunction();
//判断输入是否为空
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
//4.获取响应数据
request.onreadystatechange=function()
{
//4.1添加监听
if (request.readyState==4 && request.status==200)
{
//4.2获取响应消息并显示在界面
document.getElementById("txtHint").innerHTML=request.responseText;
}
}
//2.设置请求:
/* 参数一:请求类型GET or POST
* 参数二:请求的路径
* 参数三:是否异步,一般true,表示发送后就不再去管而去做其他事
*/
request.open("POST","checkname.jsp?",true);
//2.1如果使用的是post方式带数据,那么 这里要添加头, 说明提交的数据类型是一个经过url编码的form表单数据
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//3.发送请求:post请求需要在send方法里面写请求数据。
request.send("name="+str);
}
</script>
<body>
<h3>用户注册:</h3>
<form action="">
输入姓名: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>提示信息: <span id="txtHint"></span></p>
</body>
</html>
- 服务器端: checkname.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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String name = request.getParameter("name");
//模拟服务器端校验
if(name.equals("cyn")){
//存在用户名
out.println("<font color='red'>用户名已存在!</font>");
}
else{
//不存在用户名
out.println("<font color='green'>用户名可用!</font>");
}
%>
</body>
</html>
- 运行结果:
2.总结:
- 首先必须根据浏览器版本的不同创建Ajax引擎
var xmlhttp;
if (window.XMLHttpRequest)
{
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
xmlhttp=new XMLHttpRequest();
}
else
{
// IE6, IE5 浏览器执行代码
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
- open()方法只是初始化http请求参数,并不真正发送http请求。可以调用send()方法发送http请求。
- 根据http请求的状态,自动调用相应处理函数接收数据并在前台界面进行显示操作:xmlhttp.onreadystatechange=function(){}。
- XMLHttpRequest的属性responseText自动封装了接收到的相应文本的所有内容!