Home > Web Front-end > JS Tutorial > body text

Detailed explanation of the principles, advantages and disadvantages of Ajax

php中世界最好的语言
Release: 2018-04-04 16:53:29
Original
1434 people have browsed it

This time I will give you a detailed explanation of the principles, advantages and disadvantages of Ajax, and what are the precautions for using Ajax. The following is a practical case, let's take a look.

1. Background of ajax technology

It is undeniable that the popularity of ajax technology is due to the vigorous promotion of google, precisely because of google earth The widespread application of Ajax technology such as , Google Suggest and Gmail 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 already started to use it before. Ajax is used in some products, such as some applications in the MSDN website menu. Unfortunately, for some unknown reason, after Microsoft invented the core technology of ajax, it 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 should not be unable to see the prospects of ajax technology. The only explanation may be that its main competitor at the time The disappearance of 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. This will be discussed later when I talk about the flaws of Ajax. will also be mentioned. Now Microsoft is also aware of this problem, so it has also begun to catch up in the ajax field. For example, it launched its own ajax framework atlas, and also provided an interface for implementing asynchronous callbacks in .NET 2.0, namely the ICallBack interface. . So why is Microsoft so nervous about its lagging behind in ajax? Now let us analyze the profound meaning behind ajax technology.

2. The significance of ajax technology

We are more or less exposed to or applied to ajax in our daily development. When it comes to ajax As for the significance of technology, what we pay most attention to is undoubtedly improving the user experience. However, if we combine the future development trends of computers and the Internet, we will find that ajax technology represents this trend in some aspects. Why do you say this way? We know that since the advent of computers, desktop software has always occupied an absolutely dominant position, but the emergence and success of the Internet has caused subtle changes in all this. A considerable number of people believe that sooner or later, data and computer software will move from the desktop to the Internet. In other words, computers in the future may abandon bulky hard drives and obtain data and services directly from the Internet. I remember when I was in college, a professor once imagined such a scenario when he was giving us a class. Maybe In the future, there will be no redundant software or programs on the computer desktop, but only one IE. Although it seems that we are still far away from this day, and there are still many problems that need to be solved, I think this is not a dream. , but a reality that will be realized sooner or later. Well, the main problem is that the Internet connection is unstable. No one wants to watch their computer download data from the server bit by bit. So, does ajax solve this problem? To be honest, it is not so much ajax. Rather than solving the problem, it just masks the problem. It just acts as a buffer between the server and the client, tricking users into thinking there is no interruption in service. To be precise, ajax does not increase the speed of downloading data from the server, but just makes the wait less frustrating. But just this was enough to have a huge impact and shock, and it actually had a huge impact on desktop software. I will use an example to illustrate this point. We can compare Outlook Express and Gmail. The former is a typical desktop software, and the latter is a B/S mode implemented by ajax. In fact, the latter is slowly replacing the former. Gmail has almost the same functionality as Outlook Express when sending and receiving emails, and it does not require the installation of a client program. This is one of the main reasons why Microsoft is so afraid of the impact of Ajax, and in a survey it conducted not long ago, it regarded Google as their main competitor in the next ten years. Of course, this change will not eliminate all desktop software. None of the existing browsers can handle complex images like desktop programs such as PhotoShop. But we cannot ignore its influence and impact.

3. About the name of ajax

The full name of ajax is Asynchronous JavaScript and XML. Among them, Asynchronous means asynchronous. It is different. The synchronization method used in traditional web development.

About synchronization and asynchronous

Asynchronous transmission is character-oriented transmission, and its unit is character; while synchronous transmission is bit-oriented transmission, its unit is frame, and it transmits The clocks of the receiver and the sender are required to be consistent.

Specifically, asynchronous transmission divides bits into small groups for transmission. Generally, each group is an 8-bit character. There is a start bit and a stop bit at the head and tail of each group. During the transmission process, the clocks of the receiver and the sender do not need to be consistent. That is to say, the sending The party can send these groups at any time without the receiving party knowing when it will arrive. One of the most obvious examples is the communication between the computer keyboard and the host. When a key is pressed, an 8-bit ASCII code is sent to the host. The keyboard can send the code at any time, depending on the user's input speed. The internal hardware must Ability to receive a typed character at any time. This is a typical asynchronous transmission process. A potential problem with asynchronous transmission is that the receiver does not know when the data will arrive. Before it detects the data and responds, the first bit has passed. It's like someone unexpectedly comes up from behind and talks to you, and you don't have time to react and miss the first few words. Therefore, each asynchronous transmission of information begins with a start bit, which notifies the receiver that the data has arrived, which gives the receiver time to respond, receive and cache data bits; at the end of the transmission When, a stop bit indicates the end of the transmission of information. By convention, an idle (not transmitting data) line actually carries a signal representing a binary 1. The start bit of the step transmission causes the signal to become 0, and the other bits cause the signal to change with the transmitted data information. Finally, the stop bit changes the signal back to 1, where it remains until the next start bit arrives. For example, the number "1" on the keyboard will send "00110001" according to the 8-bit extended ASCII encoding. At the same time, a start bit needs to be added in front of the 8-bit bit and a stop bit will follow.

The bit packets transmitted simultaneously are much larger. Instead of sending each character independently, each with its own start bit and stop bit, it combines them and sends them together. We call these combinations data frames, or simply frames.

The first part of the data frame contains a set of synchronization characters, which is a unique combination of bits, similar to the start bit mentioned earlier, used to notify the receiver that a frame has arrived, but it can also Ensure that the sampling speed of the receiver is consistent with the arrival speed of bits, so that the sending and receiving parties are synchronized.

The last part of the frame is an end-of-frame marker. Like the synchronization character, it is also a unique bit string, similar to the stop bit mentioned earlier, used to indicate that there is no other upcoming data before the next frame begins.

Synchronous transmission is usually much faster than asynchronous transmission. The receiver does not have to start and stop each character. Once the frame synchronization characters are detected, it receives them as the next data arrives. In addition, the overhead of synchronous transmission is also relatively small. For example, a typical frame may have 500 bytes (i.e. 4000 bits) of data, which may only contain 100 bits of overhead. At this time, the added bits increase the total number of transmitted bits by 2.5%, which is much smaller than the 25% increase in asynchronous transmission. As the number of actual data bits in the data frame increases, the percentage of overhead bits decreases accordingly. However, the longer the data bits, the larger the buffer required to cache the data, which limits the size of a frame. In addition, the larger the frame, the longer the continuous time it occupies the transmission medium. In extreme cases, this will cause other users to wait too long.

hours. During these 10 hours, the water was not completely cut off, but the flow rate was much smaller than before. The flow rate returned to normal after 10 hours. So, which method would you choose if it were you? Apparently it's the latter.

4. The technology included in ajax

Everyone knows that ajax is not a new technology, but a combination of several original technologies hybrid. 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 javascript to bind and call.

Among the above technologies, except for the XmlHttpRequest object, all other technologies are based on web standards and have been widely used. Although XMLHttpRequest has not yet been adopted by W3C, it is already a de facto standard. , because almost all major browsers currently support it.

5. Ajax principle and XmlHttpRequest object

The principle of Ajax is simply to send an asynchronous request to the server through the XmlHttpRequest object, obtain data from the server, and then use javascript to operate 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.

So let’s start with XMLHttpRequest and see how it works.

First, let’s take a look at the properties of the XMLHttpRequest object.

Its attributes are:

onreadystatechange Event handler program for events triggered by each state change.

responseText returns the string form of data from the server process.

responseXML The DOM-compatible document data object returned from the server process.

statusThe numeric code returned from the server, such as the common 404 (not found) and 200 (ready)

status TextThe string information accompanying the status code

readyState Object status value

0 (uninitialized) The object has been created, but has not yet been initialized (the open method has not been called)

1 (Initialized) The object has been created, but 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 is being transmitted) Part of the data has been received because the response and http header are incomplete. At this time, it is obtained through responseBody and responseText There will be errors in some data.

4 (Complete) Data reception is completed. At this time, the complete response data can be obtained through responseXml and responseText.

However, due to differences between browsers, So 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.

function CreateXmlHttp()
{
//非IE浏览器创建XmlHttpRequest对象
if(window.XmlHttpRequest)
{
xmlhttp=new XmlHttpRequest();
}
//IE浏览器创建XmlHttpRequest对象
if(window.ActiveXObject)
{
try
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
try{
xmlhttp=new ActiveXObject("msxml2.XMLHTTP");
}
catch(ex){}
}
}
}
function TestAjax()
{
var data=document.getElementByIdx("username").value;
CreateXmlHttp();
if(!xmlhttp)
{
alert("创建xmlhttp对象异常!");
return false;
}
xmlhttp.open("POST",url,false);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
document.getElementByIdx("user1").innerHTML="数据正在加载...";
if(xmlhttp.status==200)
{
document.write(xmlhttp.responseText);
}
}
}
xmlhttp.send();
}
Copy after login

As shown above, the function first checks the overall status of 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 mode, 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.

Send method is used to send requests.

Knowing 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.

Now, we can probably have an understanding of the principle of ajax. 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 popular ajax controls now, such as magicajax, etc., they can return DataSet and other data types, but they are just the result of encapsulating this process. In essence, there is not much difference between them.

6. Advantages of ajax

Everyone basically has a deep understanding of the benefits that Ajax brings to us. Here I will only briefly Let’s talk about a few points:

1. The biggest point is that the page does not refresh and communicates with the server within the page, giving the user a very good experience.

2. Use asynchronous mode to communicate with the server, without interrupting the user's operation, and have a faster response capability.

3. Some of the work previously burdened by the server can be transferred to the client, using the idle capacity of the client to process it, reducing the burden on the server and bandwidth, and saving space and broadband 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, there is no need to download plug-ins or small programs.

7. Disadvantages of ajax

Now I will focus on the shortcomings of ajax, because usually we mostly pay attention to what ajax provides us The benefits include improved user experience. The shortcomings caused by ajax have been ignored.

The defects of ajax described below are all caused by it.

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. Those who have used Gmail know that the ajax technology used under Gmail solves this problem. You can go back under Gmail. However, it does not change the ajax mechanism. It just uses a stupid but effective one. The way to do this is by creating or using a hidden IFRAME to reproduce the changes on the page when the user clicks the back button to access the history. (For example, when the user clicks back in Google 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 for corporate data. This allows developers to inadvertently expose more data and server logic than before. Ajax logic can be hidden from client-side security scanning technology, allowing hackers to create new attacks from remote servers. Ajax is also difficult to avoid some known security weaknesses, such as cross-site scripting attacks, SQL injection attacks and credentials-based security vulnerabilities.

3. The support for search engines is relatively weak.

4. Destroyed the exception mechanism of the program. At least from the current perspective, ajax frameworks such as 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 traditional form submission modes 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、一些手持设备(如手机、PDA等)现在还不能很好的支持ajax,比如说我们在手机的浏览器上打开采用ajax技术的网站时,它目前是不支持的,当然,这个问题和我们没太多关系。

8、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,当然这是微软的一个竞争策略。

9.ajax应用举例

以上内容是转载高人写的资料,下面我将我在项目中实际应用给出个例子,这个例子是这样的:我参与的一个项目的值班安排模块里,选择值班人时,弹出的是个联系人树型TreeView结构图,点开哪个部门,然后部门下的联系人就展开了,原先是这样的,选择好某些联系人后,哪天白天或晚上的值班人就是这样的格式”小A,小B”,但是现在要求这样的格式”小A(部门一),小B(部门二)”这里假设小A属于部门一,小B属于部门二。由于选择联系人是纯前台javascript的操作的,这里要通过联系人userlist表中的部门id,来取得部门的名称,也就是通过前台取后台的数据,这个在系列五里我也阐述过,下面给出代码:

var param= "date=<%=stryear%>/<%=strmonth%>/" + x <%=stryear%><%=strmonth%>
+"&Type=" + type
+"&Other=" + eval_r("formData.RBOTHER"+x+".value")
+"&ZBRY=" + eval_r("formData.RBZBRY"+x+".value")
+"&ZBRYID=" + eval_r("formData.RBZBRYID"+x+".value")
+"&Demo=" + eval_r("formData.RBDEMO"+x+".value")
+"&id=" + eval_r("formData.RBZBID"+x+".value");//传递的参数
var retVal = window.showModalDialog( "chooseUsers.asp?"+param,this, "dialogWidth=280px; dialogHeight=500px; help=no; status=no; scroll=no; resizable=yes; ");
//弹出对话框取得联系人
//ajax调用服务器端方法取到部门名称
if(retVal ['userIds']!=""&& retVal ['userIds']!=null)//联系人id集合格式1,2,3,4
{
var PostUrl=" ../../../Application/CallBoard/GetDepartMentByUid.aspx?userIDs="+objRetVal['userIds']+"";//后台处理页面url
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");//新建一个xmlhttprequest对象
xmlHttp.open("POST", PostUrl, false);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send("");
var builder= xmlHttp.responseText; //将值传递回来,拼成了新格式
eval_r("formData.RBZBRY"+x+".value = '" +builder+"'");// formData.RBZBRY为一文本控件,将显示值班人员新格式
}
}
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Ajax请求async有哪些方式?应该如何使用

AJAX实现无刷新数据分页

The above is the detailed content of Detailed explanation of the principles, advantages and disadvantages of Ajax. For more information, please follow other related articles on the PHP Chinese website!

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