一:什么是Ajax
Ajax是(Asynchronous JavaScript And XML)是异步的JavaScript和xml。也就是异步请求更新技术。Ajax是一种对现有技术的一种新的应用,不是一门新语言。它是用JavaScript编写。与xml的关系就是可以读取和返回xml文件。
二:Ajax中的对象和方法说明
Ajax的核心对象就是xmlHttpRequest
XMLHttpRequest用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
1:方法
xmlHttpRequst对象利用send()和open()方法与服务器进行交互。
open(method,url,async)
send(string)
如果是post请求,必须使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中设置发送的数据:
[javascript] view plaincopy
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Bill&lname=Gates");
2 :属性
readyState
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
State
responseText
responseXML
onreadystatechange
三:Ajax运行原理(为什么要用Ajax)
ajax通过xmlhttpRequest对象执行操作,其中xmlhttpRequest对象是在浏览器中内置的一个对象
其运行原理就相当于创建了一个请求代理,通过代理去完成与服务器的交互,交互的过程中客户不需要等待,还可以进行其它的工作,交互完成以后,代理再将交互的结果返回给客户页面。
第一步:创建xmlHttpRequest对象,每个浏览器的创建不是都相同。
[javascript] view plaincopy
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
通常情况下为了兼容所有浏览器,每个都要写上。
第二步:设置open()方法和setRequestHeader()方法参数。
将请求方式,请求目的地址,和请求类型设置到open方法中,如果是post请求,则需要设置setRequestHeader()参数
第三步:发送执行
利用send方法,与服务器真正的交互执行
第四步:获得执行结果
首先判断执行是否完成,然后通过js操作dom元素,将返回的responseText返回到页面
[javascript] view plaincopy
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
四:Ajax实例(焦点离开验证用户是否存在)
利用ajax在焦点离开的时候判断注册的用户是否存在
[javascript] view plaincopy
var xmlHttp;
function createXMLHttpRequest() {
if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function validate(field) {
if (trim(field.value).length != 0) {
createXMLHttpRequest();
var url = "user_validate.jsp?userId=" + trim(field.value) + "×tamp=" + new Date().getTime();
xmlHttp.open("GET",153); font-weight: bold; background-color: inherit;">true);
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
document.getElementById("userIdSpan").innerHTML = "<font color='red'>" + xmlHttp.responseText + "</font>";
}else {
alert("请求失败,错误码=" + xmlHttp.status);
}
}
};
xmlHttp.send(null);
}else {
document.getElementById("userIdSpan").innerHTML = "";
}
}
页面部分代码:
[html] view plaincopy
<td width="78%">
input name="userId" type="text" class="text1" id="userId"
size="10" maxlength="10" onkeypress="userIdOnKeyPress()" value="<%=userId %>" onblur="validate(this)">span id="userIdSpan"</span>
td>
//后台验证方法利用jsp编写
[java] view plaincopy
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@ page import="com.bjpowernode.drp.sysmgr.manager.*" %>
<%
String userId = request.getParameter("userId");
if (UserManager.getInstance().findUserById(userId) != null) {
out.println("用户代码已经存在");
}
%