AJAX的重点是XMLHttpRequest对象。
所有现代浏览器都支持XMLHttpRequest对象。
XMLHTTPRequest用于客户端和服务器之间的异步通信
XMLHttpRequest对象可用于与后台的服务器交换数据。 这意味着可以更新网页的某些部分,而无需重新加载整个页面。
创建一个XMLHttpRequest对象
所有现代浏览器(Chrome,Firefox,IE7 +,Edge,Safari Opera)都具有内置的XMLHttpRequest对象。
创建XMLHttpRequest对象的语法:var xmlHttpObj=new XMLHttpRequest();
跨域访问
出于安全原因,现代浏览器不允许跨域访问。
这意味着该网页和它尝试加载的XML文件都必须位于同一服务器上。
The examples on W3Schools all open XML files located on the W3Schools domain.
如果要在自己的网页之一上使用上面的示例,则加载的XML文件必须位于自己的服务器上。
Internet Explorer的旧版本(IE5和IE6)
nternet Explorer的旧版本(IE5和IE6)使用ActiveX对象替代XMLHttpRequest对象:var ieOldVersion=new ActiveXObject("Microsoft.XMLHTTP");
为了处理旧版本ie浏览器,检查浏览器是否支持XMLHTTPRequest对象,如果不支持则使用ActiveXOjbect对象创建交互对象
if (window.XMLHttpRequest) {
var xmlHttpObj = new XMLHttpRequest();
} else {
var ieOldVersion = new ActiveXObject("Microsoft.XMLHTTP");
}
Request向服务器发送请求(get/post)
XMLHttpRequest对象用于与服务器交换数据。
要将请求发送到服务器,我们使用XMLHttpRequest
对象的open()
和send()
方法:
请求的方法有get
、post
GET比POST更简单,更快捷,并且可以在大多数情况下使用。
但是,在以下情况下,请始终使用POST请求:
- 请求不需要被缓存
- 发送大量数据
- 发送隐私数据
Ajax的get方法不带参数直接访问JSP
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body onload="loadXmlHttp()">
<h1>HelloWorld</h1>
<button id="myBtn">say hello</button>
<p id="demo"></p>
</body>
<script>
var xmlHttpObj;//global var
function loadXmlHttp() {
if (window.XMLHttpRequest) {
xmlHttpObj = new XMLHttpRequest();
} else {
xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
}
}
document
.getElementById("myBtn")
.addEventListener(
"click",
function() {
xmlHttpObj.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText
+ "<br>";
}
}
//xmlHttpObj.open("GET", "demo_get.jsp?time="+Math.random(), true);
xmlHttpObj.open("GET", "demo_get.jsp", true);
xmlHttpObj.send();
});
</script>
</html>
demo_get.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>
<%
java.text.SimpleDateFormat formater = new java.text.SimpleDateFormat("yyyy年MM月dd日");
String strCurrentTime = formater.format(new java.util.Date());
%>
<p>this content was requested using the GET method.</p>
<p>
Requested at:<%=strCurrentTime%></p>
</body>
</html>
result:
Ajax的get方法带参数访问JSP
xmlHttpObj.open("GET", "demo_get.jsp?username="+name+"&&country="+country, true);
ajax的post方法不带参数访问jsp
xmlHttpObj.open("POST", "demo_get.jsp", true);
xmlHttpObj.send();
ajax的post方法带参数访问jsp
xmlHttpObj.open("POST", "demo_get.jsp", true);
xmlHttpObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttpObj.send("username="+name+"&country="+country);
open方法参数url(访问的目标文件地址)
open()方法的url参数是服务器上文件的地址:
该文件可以是任何类型的文件(例如.txt和.xml),也可以是服务器脚本文件(例如.asp和.php)(可以在发送回响应之前在服务器上执行操作)。
open方法第三个参数指定是否异步
异步请求
服务器请求应异步发送。
open()
方法的async(异步)参数
应设置为true
:
By sending asynchronously, the JavaScript does not have to wait for the server response, but can instead:
execute other scripts while waiting for server response
deal with the response after the response is ready
同步请求
要执行同步请求,请将open()方法中的第三个参数更改为false:
同步请求时由于代码将等待服务器完成,因此不需要onreadystatechange函数:
同步请求示例
xmlHttpObj.open("GET", "ajax_info.txt", false);//打开请求
xmlHttpObj.send();//发送请求
document.getElementById("demo").innerHTML = xmlHttpObj.responseText
XMLHttpRequest的四个重要的属性
- onreadystatechage
- readyState
- status
- statusText
onreadystatechange属性
With the XMLHttpRequest object you can define a function to be executed when the request receives an answer.The function is defined in the onreadystatechange property of the XMLHttpResponse object:
- readyState属性保存XMLHttpRequest的状态。
0:请求未初始化
1:建立服务器连接
2:收到请求
3:处理要求
4:请求已完成且响应已准备就绪
- onreadystatechange属性定义当readyState更改时要执行的函数。
- status属性和statusText属性保存XMLHttpRequest对象的状态。
简而言之
- readyState(请求的状态)
- status(状态码)
- statusText(状态文本)
- onreadystatechange(定义当readyState属性更改时要调用的函数)
每次readyState更改时,都会调用onreadystatechange函数。
当readyState为4且状态为200时,响应准备就绪:
xmlHttpObj.open("POST", "demo_get.jsp", true);//打开请求
xmlHttpObj.send();//发送请求
xmlHttpObj.onreadystatechange = function() {//如果返回了相应,则使用onreadystatechange方法处理
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText+ "<br>";
}
}
使用回调函数处理响应
回调函数是作为参数传递给另一个函数的函数
如果网站中有多个AJAX任务,则应创建一个函数来执行XMLHttpRequest对象,并为每个AJAX任务创建一个回调函数。
函数调用应包含URL以及响应就绪后要调用的函数。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body onload="loadXmlHttp()">
<h1>HelloWorld</h1>
姓名:
<input type="text" id="username"></input>
<br> 国家:
<input type="text" id="country"></input>
<button id="myBtn">submit</button>
<button id="myBtn2">submit</button>
<div style="border:1px solid;width:300px;height:200px;padding:20px;margin:20px;" id="demo"></div>
<div style="border:1px solid;width:300px;height:200px;padding:20px;margin:20px" id="demo2"></div>
</body>
<script>
var xmlHttpObj;//global var
function loadXmlHttp() {
if (window.XMLHttpRequest) {
xmlHttpObj = new XMLHttpRequest();
} else {
xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
}
}
var name = document.getElementById("username").value;
var country = document.getElementById("country").value;
function ajaxCall(method, url, myFunction) {
xmlHttpObj.open(method, url, true);
xmlHttpObj.send();
xmlHttpObj.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
}
}
function myFunction(xmlhttp) {
document.getElementById("demo").innerHTML = xmlhttp.responseText
+ "<br>";
}
function myFunction2(xmlhttp) {
document.getElementById("demo2").innerHTML = xmlhttp.responseText
+ "<br>";
}
document.getElementById("myBtn").addEventListener("click", function() {
ajaxCall("GET", "ajax_info.txt", myFunction);
})
document.getElementById("myBtn2").addEventListener("click", function() {
ajaxCall("GET", "ajax_info.txt", myFunction2);
})
</script>
</html>
Response对象(响应对象的的属性和方法)
属性:
responseText(responseText 以字符串形式获取响应数据)
responseXML
方法:
获得所有标头信息方法:getAllResponseHeaders
获得某个标头信息方法:getResponseHeader
responseXml以XML数据的形式获取响应数据
XML HttpRequest对象具有内置的XML解析器。
responseXML属性将服务器响应作为XML DOM对象返回。
使用此属性,您可以将响应解析为XML DOM对象:
解析xml数据示例
function myFunction3(xmlhttp) {
var xmlDoc = xmlhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");
for (var i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo3").innerHTML = txt;
}