Home > Backend Development > PHP Tutorial > How AJAX works

How AJAX works

WBOY
Release: 2016-07-29 09:15:04
Original
1532 people have browsed it

1. Background of ajax technology

It is undeniable that the popularity of ajax technology is due to the vigorous promotion of google. It is precisely because of the strong promotion of ajax technology by google earth, google suggest and gmail. The widespread application of ajax has given rise to the popularity of ajax. This also makes Microsoft feel extremely embarrassed, because as early as 1997, Microsoft had invented the key technology in ajax, and when IE5 was launched in 1999, it began to support the XmlHttpRequest object , and Microsoft had previously It has begun to apply ajax in some of its products, such as some applications in the MSDN website menu. Unfortunately, for some unknown reason, after Microsoft invented the core technology of ajax, they did not see its potential and develop and promote it, but shelved it. I personally find this very strange, because with Microsoft's resources and strategic vision, it is unlikely that it cannot see the prospects of ajax technology. The only explanation may be that its main focus at the time was The disappearance of competitor Netscape has made it paralyzed and slow. After all, giants also take naps, such as IBM's strategic mistakes against Microsoft. It was this mistake that made its current competitor Google's leading position in ajax. In fact, Google's current leadership in ajax technology is beyond the reach of Microsoft. I will talk about this later. ajaxDefects will also be mentioned. Now Microsoft is also aware of this problem, so it has begun to catch up in the field of ajax, such as launching its own ajax framework atlas, and also provides an interface for implementing asynchronous callbacks in .NET2.0 , that is, the ICallBack interface. So why is Microsoft so nervous about falling behind in ajax? Now let us analyze the profound meaning behind the ajax technology.

2. What is ajax

ajax is "Asynchronous Javascript AND XML" (asynchronous JavaScript and XML), which refers to a web development technology for creating interactive web applications. ajax includes using XHTML and CSS standards to implement web pages, using DOM to achieve dynamic display and interaction, using XML for data exchange and processing, and finally using javaScript to bind and process all data. ajaxDelegates some of the server's workload to the client, uses certain capabilities of the client to process data, and reduces the user's actual and psychological waiting time. The user no longer encounters the browser being blank for a long time or even stopping due to page refresh. Poor results in response, which gives the user the best possible experience. ajaxBased on standardized XML, it is widely used and supported, making it easy to maintain and modify. ajaxIt is very convenient to call external data. When the page and data need to be separated, you can use ajax
to obtain the data.

Three, the technology included in ajax

Everyone knows that ajax

is not a new technology, but a combination of several original technologies . It is composed of the following technologies.
1. Use CSS and XHTML to express.
2. Use DOM model for interaction and dynamic display.
3. Use XMLHttpRequest to communicate asynchronously with the server. 4. Use javaS
script to bind and call.

4. The principle of ajax and the XmlHttpRequest object

ajax is simply that the XmlHttpRequest object is used to send exceptions to the server. step request, get the data from the server, and then Use javascript to manipulate the DOM and update the page. The most critical step in this is to obtain the request data from the server. To understand this process and principle, we must understand something about XMLHttpRequest. XMLHttpRequest is the core mechanism of ajax. It was first introduced in IE5 and is a technology that supports asynchronous requests. To put it simply, JavaScript can make requests to the server and process responses in a timely manner without blocking the user. Achieve no refresh effect. You can better understand the working principle of ajax through the picture below

<strong></strong><img src=

🎜🎜

How XMLHttpRequest works. The properties of the
XMLHttpRequest object are:
onreadystatechange The event handler for the event triggered each time the state changes.
responseText Returns the string form of data from the server process.
responseXML DOM-compatible document data object returned from the server process.器Status number code returned from the server, such as the common 404 (not found) and 200 (ready)
Startustext, accompanied by the state code string information
ReadyState , but it has not been initialized (the open method has not been called yet)

1 (Initialization) The object has been created, the send method has not been called yet

2 (Send data) The send method has been called, but the current status and http header are unknown

3 (Data transmission in progress) Part of the data has been received. Because the response and http header are incomplete, errors will occur when obtaining part of the data through responseBody and responseText.

4 (Completed) Data reception is completed. You can now pass Get full response data via responseXml and responseText

Due to differences between browsers, creating an

XMLHttpRequest

object may require different methods. This difference is mainly reflected between IE and other browsers. The following is a relatively standard method of creating an XMLHttpRequest object

<script language="javascript">
	var xmlHttp = null;

	//创建XMLHttpRequest<strong>对象
	function GetXmlHttpRequest()
	{
		var xmlHttp = null;
		try
		{
			xmlHttp = new XMLHttpRequest();  //对于firefox等浏览器
		}
		catch(e)
		{
			try
			{
				xmlHttp = new ActiveXObject("Msxm12.XMLHTTP"); //对于IE浏览器
			}
			catch(e)
			{
				try
				{
					xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch(e)
				{
					xmlHttp = false;
				}
			}
		}
		//返回XMLHttpRequest<strong>对象
		return xmlHttp;
	}
	
	//发出异步请求
	function sendRequest()
	{

		//获取页面表单提交的文本框的值
		var  prov_name = document.getElementById("province").value;

		if ((prov_name == null) || (prov_name == &#39;&#39;))
			return;
	
		xmlHttp = GetXmlHttpRequest();
		if (xmlHttp == null)
		{
			alert("浏览器不支持xmlHttpRequset!");
			return;
		}

		//构建请求的URL地址
		var url = &#39;18-5.php&#39;;
		url = url + "?prov=" + prov_name;
	
		//使用get()方法打开一个到url的链接,为发出的请求做准备
		xmlHttp.open("GET",url,true);

		//设置一个函数 ,当服务器完成请求后调用,该函数名为updatePage
		xmlHttp.onreadystatechange = updatePage;
		//发送请求(GET提交方式) <span style="font-family: 宋体;">POST提交方式 <span style="font-family: 宋体;">xmlHttp.send(url);
		xmlHttp.send(null);
	}

	//回调函数 处理服务器响应
	function updatePage()
	{
		//判断xmlHttpRequset()<strong>对象的readyState值是否等于4
		if(xmlHttp.readyState == 4 && xmlHttp.status ==200)
		{
		<span style="white-space: pre;">	//获取服务器返回的响应数据
			var response = xmlHttp.responseText;
			document.getElementById(&#39;city&#39;).innerHTML = response;
		}
	}
</script>
Copy after login

As shown above, the function first checks the overall status of the XMLHttpRequest and ensures that it has been completed (readyStatus =4 ), that is, the data has been sent. Then query the request status according to the server's settings. If everything is ready (status=200), then perform the following required operations.

For the two methods of XmlHttpRequest, open and send, the open method specifies: a. The type of data submitted to the server, that is, post or get.
b, requested url address and passed parameters.
c. Transmission method, false means synchronous, true means asynchronous. Default is true. If it is an asynchronous communication mode (true), the client does not wait for the server's response; if it is a synchronous mode (false), the client has to wait until the server returns a message before performing other operations. We need to specify the synchronization method according to actual needs. In some pages, multiple requests may be issued, or even large-scale, high-intensity requests that are organized, planned, and formed, and the latter one will overwrite the previous one. This Of course, you must specify the synchronization method.
d and Send methods are used to send requests.

From the workflow of XMLHttpRequest, we can see that XMLHttpRequest is completely used to issue a request to the server, and its role is limited to this, but its role is the key to the entire
ajax

implementation , because ajax is nothing more than two processes, making a request and responding to the request. And it's entirely a client-side technology. XMLHttpRequest handles the communication problem between the server and the client, which is why it is so important.
We can think of the server as a data interface, which returns a plain text stream. Of course, this text stream can be in XML format, Html, Javascript code, or Just a string. At this time, XMLHttpRequest requests this page from the server, and the server writes the text result into the page. This is the same as the ordinary web development process. The difference is that after the client obtains the result asynchronously, it is not directly displayed on the page. , but is processed by javascript first and then displayed on the page. As for many of the popular

ajax

controls, such as magicajax, etc., they can return other data types such as DataSet. They just encapsulate the result of this process. In essence, there is not much difference between them.
5. Advantages and Disadvantages of
ajax
Advantages of

ajax:

1. The biggest point is that the page does not refresh, communicates with the server within the page, and gives the user The experience was very good.
2. Use asynchronous mode to communicate with the server, without interrupting the user's operation, and have faster response capabilities.

3. Some of the work previously burdened by the server can be transferred to the client, using the client's idle capacity to process, reducing the burden on the server and bandwidth, saving space and bandwidth rental costs. And to reduce the burden on the server, the principle of

ajax

is to "fetch data on demand", which can minimize the burden on the server caused by redundant requests and responses.

4. Based on standardized and widely supported technology, no need to download plug-ins or applets. Disadvantages of

ajax:
Because most of us usually pay attention to the benefits that ajax brings to us, such as the improvement of user experience. And the shortcomings caused by ajax have been ignored. The defects of ajax explained below are all caused by its innateness.

1. ajax kills the back button, which destroys the browser's back mechanism. The back button is an important feature of a standard web site, but it doesn't work well with JavaScript. This is a serious problem caused by ajax, because users often hope to cancel the previous operation by going back. So is there any solution to this problem? The answer is yes. Anyone who has used Gmail knows that the ajax technology used under Gmail solves this problem. You can go back under Gmail, but it cannot change the mechanism of ajax. It is just a A clumsy but effective method is to create or use a hidden IFRAME to reproduce the changes on the page when the user clicks the back button to access the history. (For example, when a user searches on Google When you click back in Maps, it searches in a hidden IFRAME and then reflects the search results onto the ajax element to restore the application state to what it was at that time. ) However, although this problem can be solved, the development cost it brings is very high, which is contrary to the rapid development required by the ajax framework. This is a very serious problem caused by ajax.

2. Security issues
Technology also brings new security threats to IT companies. ajax technology is like establishing a direct channel to corporate data. This allows developers to inadvertently expose more data and server logic than before. The logic of ajax can be hidden from client-side security scanning technology, allowing hackers to establish new attacks from remote servers. In addition, ajax is also difficult to avoid some known security weaknesses, such as cross-site script attacks, SQLinjection attacks and credentials-based security vulnerabilities, etc.
3. The support for search indexengine is relatively weak.
4. Destroyed the exception mechanism of the program. At least from the current point of view, ajax frameworks like ajax.dll and ajaxpro.dll will destroy the exception mechanism of the program. Regarding this problem, I have encountered it during the development process, but after checking, there is almost no relevant introduction on the Internet. Later, I did an experiment myself, using ajax and the traditional form submission mode to delete a piece of data... which brought great difficulties to our debugging.
5. In addition, there are some other problems, such as violating the original intention of URL and resource positioning. For example, if I give you a url address, if ajax technology is used, maybe what you see under the url address is different from what I see under this url address. This is contrary to the original intention of resource positioning.
6. Some handheld devices (such as mobile phones, PDAs, etc.) currently do not support ajax very well. For example, when we open a website using ajax technology on a mobile browser, it currently does not support it. Of course, this issue has nothing to do with us.

6. Several frameworks of ajax

目前我们采用的比较多的ajax框架主要有ajax.dll,ajaxpro.dll,magicajax.dll 以及微软的atlas框架。ajax.dll和ajaxpro.dll这两个框架差别不大,而magicajax.dll只是封装得更厉害一些,比如说它可以直接返回DataSet数据集,前面我们已经说过,ajax返回的都是字符串,magicajax只是对它进行了封装而已。但是它的这个特点可以给我们带来很大的方便,比如说我们的页面有一个列表,而列表的数据是不断变化的,那么我们可以采用magicajax来处理,操作很简单,添加magicajax之后,将要更新的列表控件放在magicajax的控件之内,然后在pageload里面定义更新间隔的时间就ok了,atlas的原理和magicajax差不多。但是,需要注意的一个问题是,这几种框架都只支持IE,没有进行浏览器兼容方面的处理,用反编译工具察看他们的代码就可以知道。
除了这几种框架之外,我们平时用到的比较多的方式是自己创建xmlHttpRequest对象,这种方式和前面的几种框架相比更具有灵活性。另外,在这里还提一下aspnet2.0自带的异步回调接口,它和ajax一样也可以实现局部的无刷新,但它的实现实际上也是基于xmlhttprequest对象的,另外也是只支持IE,当然这是微软的一个竞争策略。

七、ajax简单示例

示例实现的功能是当用户在WEB页面的下拉列表框中选择某个省的名称时,会在页面上显示该省的省会名称,而此时页面并不刷新。省会名称将由服务端传送至浏览器。这个示例包含三个部分(这里的服务端是PHP程序)

1、HTML页面,包含下拉列表框和要显示省会名称的位置

2、JavaScript程序,实现发送请求和处理响应。

3、服务端的PHP程序,用来接受浏览器的请求,向浏览器传送结果数据。

(客户端)HTML页面:



<meta http-equiv="Content-Type" c charset='utf-8"'>
<title>
<strong>ajax</strong>简单应用</title>
<script language="javascript">
	var xmlHttp = null;

	//创建XMLHttpRequest<strong>对象
	function GetXmlHttpRequest()
	{
		var xmlHttp = null;
		try
		{
			xmlHttp = new XMLHttpRequest();  //对于firefox等浏览器
		}
		catch(e)
		{
			try
			{
				xmlHttp = new ActiveXObject("Msxm12.XMLHTTP"); //对于IE浏览器
			}
			catch(e)
			{
				try
				{
					xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch(e)
				{
					xmlHttp = false;
				}
			}
		}
		//返回XMLHttpRequest<strong>对象
		return xmlHttp;
	}
	
	//发出异步请求
	function sendRequest()
	{

		//获取页面表单提交的文本框的值
		var  prov_name = document.getElementById("province").value;

		if ((prov_name == null) || (prov_name == &#39;&#39;))
			return;
	
		xmlHttp = GetXmlHttpRequest();
		if (xmlHttp == null)
		{
			alert("浏览器不支持xmlHttpRequset!");
			return;
		}

		//构建请求的URL地址
		var url = &#39;18-5.php&#39;;
		url = url + "?prov=" + prov_name;
	
		//使用get()方法打开一个到url的链接,为发出的请求做准备
		xmlHttp.open("GET",url,true);

		//设置一个函数 ,当服务器完成请求后调用,该函数名为updatePage
		xmlHttp.onreadystatechange = updatePage;
		//发送请求
		xmlHttp.send(null);
	}

	//回调函数 处理服务器响应
	function updatePage()
	{
		if(xmlHttp.readyState!= 4)
		{
			document.getElementById("city").innerHTML="数据正在加载...";
		}
		//判断xmlHttpRequset()<strong>对象的readyState值是否等于4
		if(xmlHttp.readyState == 4 && xmlHttp.status ==200)
		{
			//获取服务器返回的响应数据
			var response = xmlHttp.responseText;
			document.getElementById(&#39;city&#39;).innerHTML = response;
		}
	}

</script>



<h3>请选择一个省(自治区)<h3>
</h3>
</h3>
Copy after login
(服务端)PHP程序

<?php $city_arr = array(
		&#39;ah&#39;=>'合肥',
		'fj'=>'福州',
		'gs'=>'兰州',
		'gx'=>'南宁',
		'gd'=>'广州',
		'gz'=>'贵阳',
		'hn'=>'海口',
		'hb'=>'石家庄',
		'hh'=>'郑州',
		'hlg'=>'哈尔滨',
	);

	if (empty($_GET['prov']))
	{
		echo iconv("UTF-8", "UTF-8", '<font color="red">您还没有选择省(自治区)</font>'); //注意:你的PHP文件使用的是<strong>GB2312</strong>编码保存的话,那iconv('<strong>GB2312</strong>','UTF-8','<span style="font-family: 宋体;"><font color="red">您还没有选择省(自治区)</font></span><span style="font-family: 宋体;">');</span>
	}
	else
	{
		$prov = $_GET['prov'];
		$city = $city_arr[$prov];
		echo iconv("UTF-8", "UTF-8", '所选省(自治区)省会(首府)为:'.$city); <span style="font-family: 宋体;">//注意:你的PHP文件使用的是<strong>GB2312</strong>编码保存的话,那iconv('<strong>GB2312</strong>','UTF-8','</span><span style="font-family: 宋体;">所选省(自治区)省会(首府)为:'.$city</span><span style="font-family: 宋体;">);</span><span style="font-family: 宋体;">
</span>	}
?>
Copy after login
运行效果

How AJAX works


以上就介绍了AJAX工作原理,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template