The concept of AJAX basic usage synchronous and asynchronous

Basic concepts of AJAX

Ajax full name: Asynchronous JavaScript and XML (asynchronous JavaScript and XML )

XML is an old standard. The server will return XML before. After 2010, everyone found that JSON is more convenient to use, so JSON data is returned asynchronously instead of XML data.

  • Ajax is not a new language, but a new concept that uses existing standards
  • Ajax supports smartphones very well

Ajax technology will make the page partial update, that is, the HTTP request is secretly sent, the response given by the server is secretly returned, and the page is partially refreshed.

Without refreshing the page, the browser quietly and asynchronously sends HTTP requests to the server. After the server receives the response, it sends back data (usually JSON data). After the browser receives the data, it renders the page through the DOM

The mechanism of AJAX request

Basic use

<script>
    var text = document.getElementById("text");
    var btn = document.getElementById("btn");
    btn.onclick = function () {
        // 创建一个XMLHttpRequest对象
        var xhr = new XMLHttpRequest();
        console.log(xhr)
        // 配置这个xhr对象,告诉这个对象要干什么
        xhr.onreadystatechange = function () {
            // 当xhr对象状态为4的时候
            if (xhr.readyState == 4) {
                // 让h1里面的文本为接收到的文本
                text.innerHTML = xhr.responseText
            }
        }
        // 告诉这个对象要用什么请求,请求哪个文件,是否是异步状态
        xhr.open("get", "text.txt", true);
        // 发送请求
        xhr.send(null)
    }
</script>

XMLHttpRequest object

The XMLHttpRequest object is a built-in object of the system. With the built-in system constructor new XMLHttpRequest(), all Ajax functions are encapsulated in the returned object

The first step of an Ajax request

var xhr = new XMLHttpRequest();

This constructor is not compatible with IE6. IE6 uses:

var xhr = new ActiveXObject("Microsoft.XMLHTTP")

Comprehensive writing method for ability testing

// 是能力检测,如果支持XMLHttpRequest就使用XMLHttpRequest否则使用ActiveXObject
if (window.XMLHttpRequest) {
    var xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
    var xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

At this point, after the object is created, all Ajax services are completed by the xhr object

readyState state

The readyState state value refers to the several states that AJAX has experienced, no matter whether the access is successful or not, it will respond to the step, which can be understood as the AJAX running step

  •  0-(uninitialized) send() method has not been called yet
  • 1-(loading) the send() method has been called and the request is being sent
  • 2-(Loading completed) The send() method has been executed, and all response content has been received
  • 3-(Interactive) The response content is being parsed
  • 4-(Completed) The response content is parsed and can be called on the client

When xhr.readyState sends a change, the onreadystatechange event will be triggered.

If readyState is 4 , when all the parsing have been completed, so we only care about readyState it is 4 time

open method

Use xhr.open() to configure a request. There are three parameters

  • The first parameter is the type of request, the value is " get " or " post ";
  • The second parameter indicates the file path of the request. We generally write a relative path. Why is it a relative path? Because Ajax cannot cross-domain, Ajax can only request files on the same server (cross-domain issues are mentioned separately)
  • The third parameter is a Boolean value, which indicates whether to use asynchrony. If true , it means that the file is read asynchronously; false means that the file is read synchronously

send method

Use the send() method to make a request

The internal parameter of send is the content of the upstream message. Because the get request has no message, write null

Synchronous and asynchronous concepts

When programming, there are often things that take time. For example, our disk I/O, network access, etc. will take time. At this time, there are two strategies.

The first one is to wait forever, wait until it is finished, and wait until there is a result before continuing;    →Synchronize

The second type, you can execute the following program while waiting, if the result is returned, execute the callback function        → asynchronous

Asynchronous statements must have a callback function , because it is necessary to give an entry point to the asynchronous program

The asynchronous statements that have been contacted so far are

setInterval(function(){},1000); 		//定时器
setTimeout(funcction(){},2000); 		//延时器
animate({},3000,function(){}) 		// jQuery的动画
xhr.open("get", "text.txt", true); 	//Ajax
xhr.send()

Give a few examples 

Simple example of synchronization

<script>
    var a = 0;
    while (a != 5) {
        a = parseInt(Math.random() * 10)
        console.log("正在执行,", a)
    }
    console.log("该我执行了")
</script>

Simple example of asynchrony

<script>
    var a = 0;
    setInterval(function () {
        a++;
        console.log(a)
    }, 1000)
    console.log("我x先执行了")
</script>

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/weixin_41040445/article/details/114838334