Home >Web Front-end >JS Tutorial >What is ajax? Detailed usage process of ajax (complete example included)

What is ajax? Detailed usage process of ajax (complete example included)

寻∝梦
寻∝梦Original
2018-09-10 14:20:151239browse

This article mainly introduces the definition of ajax, as well as the specific usage of ajax. Now let’s read this article together

1.What is Ajax?

The technology that allows the browser to communicate with the server without refreshing the current page is called Ajax. In the actual programming process, XMLHttpRequest is often used as a synonym for Ajax, and XMLHttpRequest is an extension of JavaScript.

2. Methods and properties:

##2.3 Programming using JavaScript language

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>HelloWorld</title>
		<script type="text/javascript">
			window.onload = function(){
				//1.为a节点添加点击事件
				document.getElementsByTagName("a")[0].onclick = function(){
					//3.创建XMLHttpRequest对象
					var request = new XMLHttpRequest();
					//4.准备请求参数url method
					var url = this.href + "?time=" + new Date();
					var method = "GET";
					//5.调用 XMLHttpRequest 对象的 open 方法
					request.open(method,url);
					//6.调用 XMLHttpRequest 对象的 send 方法
					request.send(null);
					//7.为XMLHttpRequest对象添加onreadystatechange响应函数
					request.onreadystatechange = function(){
						//8.判断响应是否完成:XMLHttpReques对象的 readState 为  4
						if(request.readyState == 4){
							//9.再判断响应是否可用: XMLHttpReques对象的status 为  200
							if(request.status == 200 || request.status == 304){
								//10.打印相应结果:responseText
								alert(request.responseText);
							}
						}
					}
					//2.取消默认行为,阻止点击页面跳转
					return false;
				}
			}
		</script>
	</head>
	<body>
		<a href="hello.txt">Hello</a>
	</body>
</html>

Using XMLHttpRequest instances to communicate with the server contains 3 keys:

①onreadystatechange event handling function:
--|

This event handling function is triggered by the server, not the user;

--|During Ajax execution , the server will notify the client of the current communication status. This is accomplished by updating the readyState of the XMLHttpRequest object. Changing the readyState property is a way for the server to operate on the client connection.

Every time the readyState attribute changes, the readystatechange event will be triggered

②open(method, url, asynch): --

|

XMLHttpRequest The object's open method allows the programmer to send a request to the server using an Ajax call.

--|method:

Request type

, a string similar to "GET" or "POST". If you just want to retrieve a file from the server without sending any data, use GET (data can be sent in the GET request by appending the query string to the URL, but the data size is limited to 2000 characters). If you need to send data to the server, use POST. --|In some cases, some browsers will cache the results of multiple XMLHttpRequest requests in the same URL. If the response to each request is different, this will lead to bad results. HereAppend the timestamp to the end of the URL to ensure the uniqueness of the URL and prevent the browser from caching the result.

--|url: Path string pointing to the file on the server you requested. Can be an absolute path or a relative path. --|asynch: Indicates whether the request should be transmitted asynchronously. The default value is true. Specify true, and there is no need to wait for a response from the server before reading the following scripts. Specify false. When the script processing passes through this point, it will stop and wait until the Ajax request is completed before continuing (if you want to see more, go to the PHP Chinese website

AJAX Development Manual

column to learn)③send(data):

--|The open method defines some details of the Ajax request. The send method can send instructions for pending requests

--|data: the string to be passed to the server. --|If you choose a GET request, no data will be sent. Just pass null to the send method: request.send(null);

--|When sending to send () method provides parameters, make sure that the method specified in open() is POST. If no data is sent as part of the request body, use null.

④setRequestHeader(header,value):

--|When the browser requests a page from the server, it will send a set of header information along with the request. These header information are a series of metadata describing the request.

The header information is used to declare whether a request is GET or POST

.

--|In Ajax requests, the work of sending header information can be completed by setRequestHeader

--|Parameter header: The name of the header; Parameter value: The value of the header.

--|If you use POST request to send data to the server, you need to set the "Content-type" header to "application/x-www-form-urlencoded" . It will tell The server is sending the data, and the data is already URL-encoded.

--|This method

must be called after open()

⑤readyState--|readyState attribute

represents the Ajax request Current status

. Its value is represented by a number. ----|0 means not initialized. The open method has not been called yet

----|1 means loading is in progress. The open method has been called, but the send method has not been called yet

----|2 means the loading is complete. send has been called. The request has started----|3 means the interaction is in progress. The server is sending response

----|4 for completion. Response sent

--|每次 readyState 值的改变,都会触发 readystatechange 事件。如果把 onreadystatechange 事件处理函数赋给一个函数,那么每次 readyState 值的改变都会引发该函数的执行。

--|readyState 值的变化会因浏览器的不同而有所差异。但是,当请求结束的时候,每个浏览器都会把 readyState 的值统一设为 4

⑥status

--|服务器发送的每一个响应也都带有首部信息。三位数的状态码是服务器发送的响应中最重要的首部信息,并且属于超文本传输协议中的一部分。

--|常用状态码及其含义:

----|404 没找到页面(not found)

----|403 禁止访问(forbidden)

----|500 内部服务器出错(internal service error)

----|200 一切正常(ok)

----|304 没有被修改(not modified)

--|在 XMLHttpRequest 对象中,服务器发送的状态码都保存在 status 属性里。通过把这个值和 200 或 304 比较,可以确保服务器是否已发送了一个成功的响应

⑦responseText

--|XMLHttpRequest 的 responseText 属性包含了从服务器发送的数据。它是一个HTML,XML或普通文本,这取决于服务器发送的内容。

--|当 readyState 属性值变成 4 时, responseText 属性才可用,表明 Ajax 请求已经结束。

⑧responseXML

--|如果服务器返回的是 XML, 那么数据将储存在 responseXML 属性中。

--|只用服务器发送了带有正确首部信息的数据时, responseXML 属性才是可用的。 MIME 类型必须为 text/xml

3.Ajax的数据格式(HTML  XML  JSON)

3.1 HTML

(1)HTML 由一些普通文本组成。如果服务器通过 XMLHttpRequest 发送 HTML, 文本将存储在 responseText 属性中。

(2)不必从 responseText 属性中读取数据。它已经是希望的格式,可以直接将它插入到页面中。

(3)插入 HTML 代码最简单的方法是更新这个元素的 innerHTML 属性。

window.onload = function(){
	var aNodes = document.getElementsByTagName("a");
	for(var i = 0;i < aNodes.length;i++){
		aNodes[i].onclick = function(){
		var request = new XMLHttpRequest();
						
		var method = "GET";
		var url = this.href;
		request.open(method,url);
		request.send(null);
						
		request.onreadystatechange = function(){
			if(request.readyState == 4){
				if(request.status == 200 || request.status == 304){
					document.getElementById("details").innerHTML = request.responseText;
				}
			}
		}
		return false;
	}
}

3.2 XML

优点:
(1)XML 是一种通用的数据格式。
(2)不必把数据强加到已定义好的格式中,而是要为数据自定义合适的标记。
(3)利用 DOM 可以完全掌控文档。
缺点:
(1)如果文档来自于服务器,就必须得保证文档含有正确的首部信息。若文档类型不正确,那么 responseXML 的值将是空的。
(2)当浏览器接收到长的 XML 文件后, DOM 解析可能会很复杂

window.onload = function(){
	var aNodes = document.getElementsByTagName("a");
	for(var i = 0;i < aNodes.length;i++){
		aNodes[i].onclick = function(){
			var request = new XMLHttpRequest();
						
			var method = "GET";
			var url = this.href;
			request.open(method,url);
			request.send(null);
						
			request.onreadystatechange = function(){
				if(request.readyState == 4){
					if(request.status == 200 || request.status == 304){
						//1获取XML文件内容
						var result = request.responseXML;
						/*
						 * 解析XML文件:<h2><a href="mailto:andy@clearleft.com">Andy Budd</a></h2>
						 *		     <a href="http://andybudd.com/">http://andybudd.com/</a>
						 */
						var name = result.getElementsByTagName("name")[0].firstChild.nodeValue;
						var website = result.getElementsByTagName("website")[0].firstChild.nodeValue;
						var email = result.getElementsByTagName("email")[0].firstChild.nodeValue;
						//创建节点,并且添加到p节点中
						var aNode = document.createElement("a");
						aNode.appendChild(document.createTextNode(name));
						aNode.href = "mailto:" + email;
									
						var h2Node = document.createElement("h2");
						h2Node.appendChild(aNode);
									
						var aNode2 = document.createElement("a");
						aNode2.appendChild(document.createTextNode(website));
						aNode2.href = website;
									
						var detailsNode = document.getElementById("details");
						detailsNode.innerHTML = "";
						detailsNode.appendChild(h2Node);
						detailsNode.appendChild(aNode2);
					}
				}
			}
			return false;
		}
	}
}

3.3 JSON

(1)JSON(JavaScript Object  Notation)一种简单的数据格式,比xml更轻巧。JSON是JavaScript原生格式,这意味着在JavaScript中处理JSON数据不需要任何特殊的API或工具包。 
(2)JSON的规则很简单:对象是一个无序的“‘名称/值’对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’对”之间使用“,”(逗号)分隔。

window.onload = function(){
	var aNodes = document.getElementsByTagName("a");
	for(var i = 0;i < aNodes.length;i++){
		aNodes[i].onclick = function(){
			var request = new XMLHttpRequest();
				
			var method = "GET";
			var url = this.href;
			request.open(method,url);
			request.send(null);
				
			request.onreadystatechange = function(){
				if(request.readyState == 4){
					if(request.status == 200 || request.status == 304){
						var jsonStr = request.responseText;
						var jsonObject = eval("(" + jsonStr + ")");
							
						var name = jsonObject.person.name;
						var website = jsonObject.person.website;
						var email = jsonObject.person.email;
							
						var aNode = document.createElement("a");
						aNode.appendChild(document.createTextNode(name));
						aNode.href = "mailto:" + email;
							
						var h2Node = document.createElement("h2");
						h2Node.appendChild(aNode);
							
						var aNode1 = document.createElement("a");
						aNode1.appendChild(document.createTextNode(website));
						aNode1.href = website;
							
						var detailsNode = document.getElementById("details");
						detailsNode.innerHTML = "";
						detailsNode.appendChild(h2Node);
						detailsNode.appendChild(aNode1);
					}
				}
			}
						
			return false;
		}
	}
}

4.使用jQuery实现Ajax技术

jQuery 对 Ajax 操作进行了封装, 在 jQuery 中最底层的方法时 $.ajax(), 第二层是 load(), $.get() 和 $.post(), 第三层是 $.getScript() 和 $.getJSON()。

4.1 load() 方法

$(function(){
	$("a").click(function(){
		var url = this.href;
		var args = {"time":new Date()};
		$("#details").load(url);
					
		return false;
	});
})

(1)load() 方法是 jQuery 中最为简单和常用的 Ajax 方法, 能载入远程的 HTML 代码并插入到 DOM 中. 它的结构是: load(url[, data][,callback]),其中url:String类型,请求HTML页面的URL地址;data(可选):Object类型,发送到服务器的key/value数据;callback(可选):Function类型,请求完成时的回调函数,无论请求成功还是失败。

(2)如果只需要加载目标 HTML 页面内的某些元素, 则可以通过 load() 方法的 URL 参数来达到目的. 通过 URL 参数指定选择符, 就可以方便的从加载过来的 HTML 文档中选出所需要的内容. load() 方法的 URL 参数的语法结构为 “url selector”(注意: url 和 选择器之间有一个空格)

$(function(){
	$("a").click(function(){
	//选择返回HTML结果页面中的h2后代a元素
	var url = this.href + " h2 a";
	var args = {"time":new Date()};
	$("#details").load(url);
					
	return false;
	});
})

(3)传递方式: load() 方法的传递参数根据参数 data 来自动自定. 如果没有参数传递, 采用 GET 方式传递, 否则采用 POST 方式

(4)对于必须在加载完才能继续的操作, load() 方法提供了回调函数, 该函数有三个参数: 代表请求返回内容的 data; 代表请求状态的 textStatus 对象和 XMLHttpRequest 对象

4.2$.get()或$.post() 方法

4.2.1加载XML数据

			$(function(){
				$("a").click(function(){
					var url = this.href;
					args = {"time" : new Date()};
					$.get(url,args,function(data){
						var name = $(data).find("name").text();
						var email = $(data).find("email").text();
						var website = $(data).find("website").text();
						
						$("#details").empty()
						             .append("<h2><a href=&#39;mailto:" + email + "&#39;>" + name +"</a></h2>")
						             .append("<a href=&#39;" + website + "&#39;>" + website + "</a>");
					})
					return false;
				});
			})

4.2.2加载HTML数据

			$(function(){
				$("a").click(function(){
					var url = this.href;
					var args = {"time" : new Date()};
					$.get(url,args,function(data){
						$("#details").empty();
						$(data).appendTo($("#details"));
					});
					
					return false;
					
				});
			})

4.2.3加载JSON数据

			$(function(){
				$("a").click(function(){
					var url = this.href;
					args = {"time" : new Date()};
					$.get(url,args,function(data){
						var name = data.person.name;
						var email = data.person.email;
						var website = data.person.website;
						
						$("#details").empty()
						             .append("<h2><a href=&#39;mailto:" + email + "&#39;>" + name +"</a></h2>")
						             .append("<a href=&#39;" + website + "&#39;>" + website + "</a>");
					},"JSON")
					return false;
				});
			})

(1)$.get() 方法使用 GET 方式来进行异步请求. 它的结构是: $.get(url[, data][, callback][, type]),其中:url:String类型,请求HTML页面的URL地址;data(可选):Object类型,发送到服务器的key/value数据;callback(可选):Function类型,请求完成时的回调函数,无论请求成功还是失败;type(可选):String类型,服务器返回内容的格式,可以是xml,json,html,text等类型。

(2)$.get() 方法的回调函数只有两个参数: data 代表返回的内容, 可以是 XML 文档, JSON 文件, HTML 片段等; textstatus 代表请求状态, 其值可能为: succuss, error, notmodify, timeout 4 种.

(3)$.get()  和 $.post() 方法时 jQuery 中的全局函数, 而 find() 等方法都是对 jQuery 对象进行操作的方法

5.$.getJSON()方法

			$(function(){
				$("a").click(function(){
					var url = this.href;
					args = {"time" : new Date()};
					$.getJSON(url,args,function(data){
						var name = data.person.name;
						var email = data.person.email;
						var website = data.person.website;
						
						$("#details").empty()
						             .append("<h2><a href=&#39;mailto:" + email + "&#39;>" + name +"</a></h2>")
						             .append("<a href=&#39;" + website + "&#39;>" + website + "</a>");
					});
					return false;
				});
			})

本篇文章到这就结束了(想看更多就到PHP中文网AJAX使用手册栏目中学习),有问题的可以在下方留言提问。

The above is the detailed content of What is ajax? Detailed usage process of ajax (complete example included). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn