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

Detailed explanation of how ajax works

php中世界最好的语言
Release: 2018-04-03 10:06:28
Original
1414 people have browsed it

This time I will bring you a detailed explanation of the working principle of ajax, and what are the precautions when using ajax. The following is a practical case, let's take a look.

AJAX is a technology for creating fast, 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.

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

Use CSS and XHTML to represent.

Use DOM model for interaction and dynamic display.

Use XMLHttpRequest to communicate asynchronously with the server.

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 A de facto standard as almost all major browsers currently support it.

2. How to create ajax

The principle of Ajax is simply to send an asynchronous request to the server through the XmlHttpRequest object and obtain data from the server. 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. Creating ajax natively can be divided into the following four steps.

1. Create an XMLHttpRequest object

All modern browsers (IE7+, Firefox, Chrome, Safari and Opera) have built-in XMLHttpRequest objects.

Syntax for creating XMLHttpRequest objects:

var xhr = new XMLHttpRequest();
Copy after login

Older versions of Internet Explorer (IE5 and IE6) use ActiveX objects:

var xhr = new ActiveXObject("Microsoft.XMLHTTP");
Copy after login

To cope with all modern browsers, including IE5 and IE6, please check whether the browser supports the XMLHttpRequest object. If supported, creates an XMLHttpRequest object. If it is not supported, create an ActiveXObject:

var xhr;
if(XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
Copy after login

2. Prepare the request

Initialize the XMLHttpRequest object and accept three parameters:

xhr.open(method,url,async);
Copy after login

First Each parameter represents a string representing the request type , and its value can be GET or POST.

GET request:

xhr.open("GET",demo.php?name=tsrot&age=24,true);
Copy after login

POST request :

xhr.open("POST",demo.php,true);
Copy after login

The second parameter is the URL to which the request is to be sent.

The third parameter is true or false, indicating whether the request is issued in asynchronous or synchronous mode. (Default is true, false is generally not recommended)

false: Requests issued in synchronous mode will suspend the execution of all javascript code until the server gets a response. If the browser is connecting to the network or downloading a file If something goes wrong, the page will hang forever.
true: For requests issued in asynchronous mode, while the request object is sending and receiving data, the browser can continue to load the page and execute other javascript codes

3. Send a request

xhr.send();

Generally, the parameters submitted using Ajax are mostly simple strings. You can directly use the GET method to write the parameters to be submitted into the url parameter of the open method. At this time The parameters of the send method are null or empty.

GET request:

xhr.open("GET",demo.php?name=tsrot&age=24,true);
xhr.send(null);
Copy after login

POST request:

If you need to POST data like an HTML form, use setRequestHeader() to add HTTP headers. Then specify the data you want to send in the send() method:

xhr.open("POST",demo.php,true);
xhr.setRequestHeder("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
xhr.send("name="+userName+"&age="+userAge);
Copy after login

4. Process the response

xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
console.log(xhr.responseText);
}
}
Copy after login

onreadystatechange event:

When the request is When sending to the server, we need to perform some response-based tasks. Whenever readyState changes, the onreadystatechange event is triggered.

readyState attribute:

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

1: The open() method has been called, but the request has not been sent.

2:请求已经发送,标题和状态已经收到,并可用。

3:接收到来自服务器的响应。

4:接收完请求数据,表示已经完成请求。

status属性:

200:”OK”

404: 未找到页面

responseText:获得字符串形式的响应数据

responseXML:获得 XML 形式的响应数据

返回值一般为json字符串,可以用JSON.parse(xhr.responseText)转化为JSON对象。

5、完整例子

demo.html

var xhr;
if(XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
};
xhr.open("GET","./data.json",true);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
console.log(JSON.parse(xhr.responseText).name);
}
}
Copy after login

data.json

{
"name":"tsrot",
"age":24
}
Copy after login

三、ajax应用场景

场景 1. 数据验证

场景 2. 按需取数据

场景 3. 自动更新页面

四、ajax优缺点

优点:

1、页面无刷新,用户体验好。

2、异步通信,更加快的响应能力。

3、减少冗余请求,减轻了服务器负担

4、基于标准化的并被广泛支持的技术,不需要下载插件或者小程序。

缺点:

1、ajax干掉了back按钮,即对浏览器后退机制的破坏。

2、存在一定的安全问题。

3、对搜索引擎的支持比较弱。

4、破坏了程序的异常机制。

5、无法用URL直接访问。

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

推荐阅读:

AJAX请求数组应该如何实现

在Ajax中怎样清除缓存

The above is the detailed content of Detailed explanation of how ajax works. For more information, please follow other related articles on the PHP Chinese website!

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