Quick Start will get to know Ajax [article]

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_44253336/article/details/102646640

1. What is AJAX?

AJAX = Asynchronous JavaScript and XML.

AJAX is a technique for creating fast dynamic web pages.

By exchanging small amounts of data with the server behind the scenes, AJAX can make asynchronous page updates. This means that, for certain parts of the page to be updated without reloading the entire page.

The traditional web page (do not use AJAX) If you need to update the entire page surface content, essential overloaded.

AJAX it allows us to get the latest content directly to the server using JavaScript without having to reload
the page. Let Web better user experience closer to desktop applications.

To put it plainly, AJAX is a browser provides a set of API, we can call JavaScript in order to achieve control through code request and response. For network programming.

2. Quick Start

Ajax is very easy to use, we can use the analogy we usually browsers, it normally takes four steps you can get to the back-end response over the content.

//步骤1: 创建一个 XMLHttpRequest 类型的对象 ———— 相当于我们平时打开一个浏览器
var xhr = new XMLHttpRequest();
//步骤2:  open打开一个与网址之间的联系 ———— 相当于在地址栏输入网址访问
xhr.open('GET','./time.php');
//步骤3:  send通过连接发送一次请求 ———— 相当于回车或者点击访问发送请求
xhr.send(null);
//步骤4:  指定 xhr 状态发生变化的时候的处理函数 ———— 相当于处理网页呈现后的操作 
xhr.onreadystatechange = function () {
// 通过 xhr 的 readyState 判断此次请求的响应是否接收完成
	if (xhr.readyState === 4 && xhr.status=== 200) { //如果是请求已完成,并且响应已就绪
	// 通过 xhr 的 responseText 获取到响应的响应体
	console.log(this)
    }
}

This completes all operations of Ajax friends.

2.1 AJAX work flow chart

Here Insert Picture Description

2.2 readyState 和status

Since readystatechange event is triggered when xhr object state changes (not just in getting a response), which means that this event will be triggered multiple times, so we need to understand the meaning of each state represents the value of:
Here Insert Picture Description
Notes: onreadystatechange event is trigger 5 (0--4), corresponding to each change of readyState.

By understanding the meaning of each state value, we can conclude that, at the time equal to readyState 4 has been completed requests, so we usually judge whether or not equal to 4, so as to have to get a complete response content.

3. Specific usage

3.1 GET request

Usually a GET request process, the parameters are passed? Parameter passed through URL address.

var xhr = new XMLHttpRequest()
// GET 请求传递参数通常使用的是问号传参
// 这里可以在请求地址后面加上参数,从而传递数据到服务端
xhr.open('GET', './delete.php?id=1')
// 一般在 GET 请求时无需设置响应体,可以传 null 或者干脆不传
xhr.send(null)
xhr.onreadystatechange = function () {
if (this.readyState === 4 && status === 200) {
console.log(this.responseText)
}
}
// 一般情况下 URL 传递的都是参数性质的数据,而 POST 一般都是业务数据

3.2. POST request

POST request process, and are based on the data request bearer body to be submitted.

var xhr = new XMLHttpRequest()
// open 方法的第一个参数的作用就是设置请求的 method
xhr.open('POST', './add.php')
// 设置请求头中的 Content‐Type 为 application/x‐www‐form‐urlencoded
// 标识此次请求的请求体格式为 urlencoded 以便于服务端接收数据
xhr.setRequestHeader('Content‐Type', 'application/x‐www‐form‐urlencoded')
// 需要提交到服务端的数据可以通过 send 方法的参数传递
// 格式:key1=value1&key2=value2
xhr.send('key1=value1&key2=value2')
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
console.log(this.responseText)
}
}

3.3 Select GET or POST?

Compared with POST, GET easier and faster, and can be used in most cases.

However, in the following cases, please use the POST request:

  1. Can not use the cache files (files or update the database on the server)
  2. Sending large amounts of data (POST not limit the amount of data) to the server
  3. When sending the user input contains unknown character, POST is more stable and more reliable than the GET

3.4 synchronous and asynchronous

There are three parameters in the open method, wherein the third parameter is set by an asynchronous request is Ajax or synchronization request, which is a bool value is not filled, the default is true. Asynchronously executed. If you need to synchronize execution can be achieved by passing false.

That in the end what is synchronous or asynchronous it? We explain through a small example of life.

Sync: When you line up to buy lottery tickets, you can only line up to buy lottery tickets, half-way can not do other things, can only do froze, waiting for completion before the next step.

Asynchronous: when you buy a lottery ticket queue, you can do some other things, such as playing phone, play games, rather than waiting

console.log('before ajax')
var xhr = new XMLHttpRequest()
// 默认第三个参数为 true 意味着采用异步方式执行
xhr.open('GET', './time.php', true)
xhr.send(null)
xhr.onreadystatechange = function () {
	if (this.readyState === 4) {
	// 这里的代码最后执行
	console.log('request done')
	}
}
console.log('after ajax')

If executed synchronously, the code will be stuck in xhr.send () this step:

console.log('before ajax')
var xhr = new XMLHttpRequest()
// 同步方式
xhr.open('GET', './time.php', false)
// 同步方式 执行需要 先注册事件再调用 send,否则 readystatechange 无法触发
xhr.onreadystatechange = function () {
	if (this.readyState === 4) {
	// 这里的代码最后执行
	console.log('request done')
	}
}
xhr.send(null)
console.log('after ajax')

Not recommended async = false, but for some small request, is also possible.

Remember, JavaScript will wait until the server response is ready before continuing execution. If the server is busy or slow, or stop an application hang.

When you use the async = false, you must send a request in the send () before registering readystatechange (regardless of synchronous or asynchronous) --- In order to make this event can be more reliable (certain trigger), must first register!

xmlhttp.open("GET","test1.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

The next chapter we will continue to explain the response processing and packaging data format, if this article helpful to you, remember that the point of a walk praise yo ~ Thank you


If you are studying the front end of the road, remember to focus on the bloggers, learn more about the front end of knowledge -

Bloggers Home Poetic Code

Guess you like

Origin blog.csdn.net/weixin_44253336/article/details/102646640