一、XMLHttpRequest对象
1、是ajax的基础,所有现代浏览器均支持 XMLHttpRequest 对象(IE5 和 IE6 使用 ActiveXObject)。
XMLHttpRequest 用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
2、创建 XMLHttpRequest对象
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
二、向服务器发送数据,XMLHttpRequest 对象的 open() 和 send() 方法
xmlhttp.open("GET","test.jsp",true);
xmlhttp.send();
open(method,url,async)
method:请求的类型;GET 或 POSTurl:文件在服务器上的位置async:true(异步)或 false(同步)
一个简单的get请求:
xmlhttp.open("GET","test.jsp?fname=Bill&lname=Gates",true);
xmlhttp.send();
一个简单的post请求:
xmlhttp.open("POST","test.jsp?fname=Bill&lname=Gates",true);
xmlhttp.send();
如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据:
xmlhttp.open("POST","test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Bill&lname=Gates");
三、响应函数onreadystatechange中获得来自服务器的响应,使用 XMLHttpRequest 对象的 responseText获得字符串形式的响应数据。 或 responseXML 属性获得 XML 形式的响应数据。。
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
XMLHttpRequest 对象的三个重要的属性:
onreadystatechange:存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
readyState:存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。0: 请求未初始化;1: 服务器连接已建立;2: 请求已接收;3: 请求处理中;4: 请求已完成,且响应已就绪
status:200: "OK";404: 未找到页面
注意:onreadystatechange 事件被触发 5 次(0 - 4),对应着 readyState 的每个变化。
四、responseText示例:
1、创建index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >
<title>My JSP 'test.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/ajax/text.jsp?fname=Bill&lname=Gates", true);
xmlhttp.send();
}
</script>
</head>
<body>
<button type="button" οnclick="loadXMLDoc()">请求数据</button>
<div id="myDiv"></div>
</body>
</html>
2、创建text.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >
<title>My JSP 'test.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<%
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
response.getWriter().write(fname+" "+lname+":hello world!");
%>
</body>
</html>
当点击index.jsp页面的"请求数据"按钮时,会调用loadXMLDoc函数,异步加载text.jsp返回的数据,得到结果:Bill Gates:hello world!
五、使用callback 函数,是一种以参数形式传递给另一个函数的函数。
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
{
loadXMLDoc("/ajax/text.jsp?fname=Bill&lname=Gates",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" οnclick="myFunction()">通过 AJAX 改变内容</button>
</body>
</html>
六、struts2 和 ajax 结合使用
1、创建index.jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >
<title>My JSP 'ajax.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript">
function showHint(str)
{
var xmlhttp;
if (str.length==0){
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/ajax/struts2/ajax.action?str="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<h3>请在下面的输入框中键入字母(A - Z):</h3>
<form action="">
姓氏:<input type="text" id="txt1" οnkeyup="showHint(this.value)" />
</form>
<p>建议:<span id="txtHint"></span></p>
</body>
</html>
2、配置web.xml和struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="hzb" namespace="/struts2" extends="struts-default">
<action name="ajax" class="com.hzb.AjaxAction">
</action>
</package>
</struts>
3、创建Action类
package com.hzb;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class AjaxAction extends ActionSupport{
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public String execute(){
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=utf-8");
try {
String responseStr = "";
if(str.startsWith("a")){
responseStr = "aaaaaaaaaa黄";
}else if(str.startsWith("b")){
responseStr = "bbbbbbbbbb黄";
}else{
responseStr = "cccccccccc黄";
}
response.getWriter().write(responseStr);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
部署到web服务器后,访问http://localhost:8080/ajax/index.jsp,就可以测试效果了。
七、ajax小应用技巧
1、缓存问题
在Firefox浏览器中,XMLHTTPRequest对象向相同的url发送请求时,浏览器每次都会向服务器发送请求,不存在缓存的问题,而IE浏览器如果url请求地址相同时,浏览器会读取其缓存中的内容进行响应,而不再向服务器发送请求,解决浏览器缓存的办法是:在url后面加上时间戳参数,使浏览器认为请求的url不同,而不再读取缓存。
/ajax/struts2/ajax.actiont?t =
Math.random()
2、AJAX传递中文乱码问题
当使用AJAX处理中文参数时,浏览器会显示乱码,解决方法有如下两种解决方案:
方案一:
页面端:使用encodeURI(参数)对中文参数进行编码。
服务器端:使用new String(参数.getBytes(“ISO8859-1”),”UTF-8”);对参数进行重新编码为UTF-8。
缺点:服务器可能不是使用ISO8859-1,硬编码不方便修改。
方案二:
页面端:使用encodeURI(encodeURI(参数))对中文参数进行两次编码。
服务器端:使用URLDecoder.decode(参数,”UTF-8”);进行UTF-8解码。
此方法是推荐使用。