This article mainly introduces the background definition of ajax, as well as a summary of personal use of ajax. Now let us take a look at this article.
This article has the following sections Content:
What is AJAX
The background of AJAX
The principle of AJAX
Definition of AJAX
Development steps of AJAX
A simple demo
Advantages and Disadvantages of AJAX Technology
What is AJAX?
By looking at Wikipedia, we can see this passage:AJAX stands for "Asynchronous JavaScript and XML" (asynchronous JavaScript and XML technology), which refers to a set of browser-side web development technologies that combine multiple technologies.
So, now we have a general impression, AJAX = JavaScript XML. We should all be familiar with js and xml.
Background of the emergence of AJAX
Looking back on our development journey, in the original development process using Servlet JSP JavaBean, our web application allowed users to fill in and submit forms (Form) on the web page. To send a request (Request) to the web server. The server receives the request, processes the incoming form, and returns a response (Response). After the browser obtains the response, it displays the page on the browser through parsing, thus completing an interaction between the user and the server.
However, there are some problems with this model. Now look at this example: the browser displays the user login interface. When the user enters the username, password and verification code, the data is sent to the server. Suppose we process the request in the Servlet and find that the username and password do not match. We What’s next?
We will return the page and the error message response to the browser again. The browser will display the information after parsing the response. Using such a development process, no matter how perfect the business implementation is, there will be some inherent problems:
First of all, is a waste of bandwidth. Except for the part that displays the error message, all other elements in the two pages are the same.
Secondly, the user experience is poor. Suppose the user accidentally enters the wrong user name in the form. After submitting the form, the page will be refreshed after a period of time and the user name is incorrect. In this way, the user will have to re-enter the user name and Password, the experience is extremely unfriendly. When the user's Internet speed is relatively slow, the user experience will be even worse.
So is there any way to solve this problem? That is, can we get feedback when the user just enters their username?
The general idea of AJAX
There was no way before the XMLHttpRequest object of js appeared, but after it appeared, the predecessors thought of a better solution, namely: use XMLHttpRequest The object serves as an Agent to send requests to the server, and uses it to receive data returned by the server. In this way, data interaction can be completed without jumping to the page, and only a small amount of necessary data needs to be transmitted, so the requirements for network speed are also lower.
However, there are still two problems that have not been solved:
1. How to dynamically change the page based on the data returned by the server to achieve interaction with the user?
2. How to specify the data format sent back by the server to make it more versatile and reduce the amount of transmission as much as possible?
For 1: The predecessors chose to use JavaScript. I personally understand that there are two reasons for this. First, JavaScript is popular enough, and almost all mainstream browsers provide support for JavaScript. Second, JavaScript can pass through the DOM. Programmatically change the content of web pages dynamically.
For 2: The predecessors chose XML, I think it may be because its syntax is strict enough, its semantics is clear, and it is more versatile. But I think the transmitted data format has no impact on using AJAX. For example, we can choose to transmit Json to transmit less data, or even choose to transmit a meaningful string, as long as the server-side and browser-side developers agree on the format.
AJAX definition
Now, we can define AJAX: AJAX is a technology for creating fast and dynamic web pages. AJAX enables web pages to update asynchronously by exchanging small amounts of data with the server in the background. This means that parts of a web page can be updated without reloading the entire page.
Development steps of AJAX technology
Through the above introduction, we know the ideas to solve the traditional problem of resource waste. Now let’s take a look at how to achieve it!
For the implementation of AJAX, you can check out W3School's introduction to AJAX
The following is my brief summary of the AJAX implementation steps:
1. We need an XMLHttpRequest object. (We all know that many standards of IE lower version browsers are incompatible with mainstream standards. Unfortunately, the same is true for the XMLHttpRequest object...)
Therefore, the acquisition process of an XMLHttpRequest object is as follows:
var httpXml = null; if(window.XMLHttpRequest){ httpXml = new XMLHttpRequest(); //针对现代浏览器,IE7及以上版本 }else if(window.ActiveXObject){ httpXml = new ActiveXObject("Microsoft.XMLHTTP"); //针对IE5,IE6版本 }
2. We need to register the operation it wants to perform for this XMLHttpRequest object (through callback), and check the status of the message based on the returned request status and HTTP status code, and determine what we want to do under what circumstances. kind of operation. (If you want to see more, go to the PHP Chinese website AJAX Development Manual column to learn)
This process is like this:
//为XMLHttpRequest对象的onreadystatechange属性注册 httpXml.onreadystatechange=function(){ // 在回调函数中根据请求状态与返回的HTTP状态码来选择相应的操作处理数据 if(httpXml.readyState==4&&httpXml.status==200){ alert(httpXml.responseText); } };
3. We need to set the parameters for request sending.
This process is like this:
//函数原型:open(method,url,async,username,password) //method --->请求方式:GET,POST或HEAD //url --->请求的地址 GET提交方式可以在后面加上参数 //async --->请求是否异步执行,true---异步,false---同步 默认为true //username,password --->可选,为url所需的授权提供认证资格。如果不为空,会覆盖掉url中指定的资格 httpXml.open("GET","http://localhost:8080/aaa/MyServlet",true);
4. It’s time to actually send the request!
// 参数为请求参数,POST提交内容格式为--->"username=taffy&password=666",GET为----->空 // 注意:若为POST请求方式,还需设置一个http请求头(应该位于open之后,send之前) // 即 setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded"); 标志form表单的enctype属性 httpXml.send(null);
这样,一个简单的AJAX过程就完成了。
一些没有介绍的小知识点:
//XMLHttpRequest属性 responseText 得到返回的文本信息 responseXML 得到返回的XML信息 //XMLHttpRequest的方法 getResponseHeader() 得到指定头部信息 getAllResponseHeaders() 将 HTTP响应头部作为未解析的字符串返回 //XMLHttpRequest的控制方法 abort() 取消当前响应,关闭连接,将readyState置0
下面是我做的一个简单的Demo:
<!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><script type="text/javascript"> <!-->onload:页面加载完成后调用 <--> window.onload = function(){ var user = document.getElementById("my_user"); //获取XMLHttpRequest对象 var httpXml = null; if(window.XMLHttpRequest){ httpXml = new XMLHttpRequest(); //针对现代浏览器,IE7及以上版本}else if(window.ActiveXObject){ httpXml = new ActiveXObject("Microsoft.XMLHTTP"); //针对IE5,IE6版本 } user.onblur=function(){ httpXml.onreadystatechange=function(){ if(httpXml.readyState==4&&httpXml.status==200){ if(httpXml.responseText!="true"){ alert("用户名不存在"); } } }; httpXml.open("GET","http://localhost:8080/aaa/MyServlet?user="+user.value,true); httpXml.send(null); }</script></head><body> <form action="http://localhost:8080/aaa/AnotherServlet"> <input type="text" name="username" id="my_user"> <input type="text" name="password" id="my_pass"> <input type="submit" value="提交"> </form></body></html>
import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Servlet implementation class MyServlet */@WebServlet("/MyServlet")public class MyServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public MyServlet() { super(); } @override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String username = request.getParameter("user"); if (username!=null&&!username.equals("")) { if (username.equals("admin")) { out.write("true"); }else { out.write("false"); } }else { out.write("false"); } out.close(); } @override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
* 下面对AJAX的优缺点进行一下总结:*
优点:
能在不更新整个页面的前提下维护数据。这使得Web应用程序更为迅捷地回应用户动作,并避免了在网络上发送那些没有改变的信息。
缺点:
1.它可能破坏浏览器的后退功能。在动态更新页面的情况下,用户无法回到前一个页面状态,这是因为浏览器仅能记下历史记录中的静态页面(现代浏览器一般都可以解决这个问题);
2.使用动态页面更新使得用户难于将某个特定的状态保存到收藏夹中。
本篇文章到这就结束了(想看更多就到PHP中文网AJAX使用手册栏目中学习),有问题的可以在下方留言提问。
The above is the detailed content of How did ajax appear? How is ajax developed? (Summary). For more information, please follow other related articles on the PHP Chinese website!