


How to implement AJAX, JSONP and DOM loading completion events in native js
1. JS native Ajax
ajax: a way to request data without refreshing the entire page;
The technical core of ajax is the XMLHttpRequest object;
ajax request process: create an XMLHttpRequest object, connect to the server, send a request, and receive response data ;
The following simply encapsulates a function, which will be explained later
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
|
1. Create
1.1, IE7 and above support native XHR objects, so you can use it directly: var oAjax = new XMLHttpRequest();
In 1.2, IE6 and previous versions, the XHR object is implemented through an ActiveX object in the MSXML library. Some books detail three different versions of such objects in IE, namely MSXML2. =new ActiveXObject ('Microsoft. Never used);
2.2. The GET request method submits data to the server through URL parameters, and POST submits the data to the server as send parameters;
2.3. In the POST request, before sending the data , to set the content type submitted by the form;
2.4. The parameters submitted to the server must be encoded through the encodeURIComponent() method. In fact, in the parameter list "key=value" form, both key and value need to be encoded, because Will contain special characters. Each time a request is made, a "v=xx" string will be spelled into the parameter list. This is to reject caching and request directly to the server every time.
encodeURI(): used to encode the entire URI. Special characters that belong to the URI will not be encoded, such as colons, forward slashes, question marks, and pound signs; its corresponding decoding function decodeURI();
encodeURIComponent() : Used to encode a certain part of the URI, and will encode any non-standard characters it finds; its corresponding decoding function decodeURIComponent(); 3. Receiving
3.1. After receiving the response, the response data The XHR object will be automatically filled in, and the relevant attributes are as follows
responseXML: if the content type of the response is "text/xml" or "application/xml", this attribute will be saved The corresponding xml data is the document type corresponding to XML;
status: response HTTP status code; statusText: description of HTTP status;
3.2. The readyState attribute of the XHR object represents the current active stage of the request/response process. This attribute The values are as follows
0-not initialized, the open() method has not been called yet;
1-started, the open() method has been called, the send() method has not been called;
3-Receive, part of the response data has been received;
4-Complete, all response data has been received;
As long as the value of readyState changes, the readystatechange event will be called. (In fact, for logical smoothness, you can Put readystatechange after send, because when sending, requesting the server, network communication will take place, which takes time. It is also possible to specify the readystatechange event handler after send. I usually use it this way, but for the sake of standardization and cross-browser compatibility, it is still Specify it before opening).
3.3. In the readystatechange event, first determine whether the response is received, and then determine whether the server successfully processed the request. xhr.status is the status code. Status codes starting with 2 are successful. 304 means getting it from the cache. The above The code adds a random number to each request, so the value will not be retrieved from the cache, so there is no need to judge this status.
4. Ajax requests cannot cross domains!
2. JSONP
JSONP (JSON with Padding) is a cross-domain request method. The main principle is to take advantage of the cross-domain request feature of the script tag, send the request to the server through its src attribute, the server returns the js code, the web page accepts the response, and then executes it directly. This is the same as the principle of referencing external files through the script tag. the same.
JSONP consists of two parts: callback function and data. The callback function is generally controlled by the web page and sent to the server as a parameter. The server combines the function and data into a string and returns it.
For example, the web page creates a script tag and assigns its src value to http://www.superfiresun.com/json/?callback=process. At this time, the web page initiates a request. The server puts together the data to be returned and passes it in as the parameters of the function. The format of the data returned by the server is similar to "process({'name':'superfiresun'})". The web page receives the response value because the requester is script. So it is equivalent to calling the process method directly and passing in a parameter.
Looking at the data returned in the response, JSONP has one more callback function than the ajax method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
|
1、因为 script 标签的 src 属性只在第一次设置的时候起作用,导致 script 标签没法重用,所以每次完成操作之后要移除;
2、JSONP这种请求方式中,参数依旧需要编码;
3、如果不设置超时,就无法得知此次请求是成功还是失败;
三、模仿JQuery中的ready()事件
1、DOMContentLoaded事件,在DOM树加载完成之后立即执行,始终会在load之前执行。
IE9+、FF、Chrome、Safari3.1+和Opera9+都支持该事件。
对于不支持该事件的浏览器,可以使用如下代码:
setTimeout(function(){
// 代码块}, 0) ;
DOMContentLoaded 事件只能通过 DOM2 级方式添加,即采用addEventListener()/attachEvent() 方式添加才能够使用。事件对象不会提供任何额外信息。
2、readystatechange事件
IE为DOM文档中的某些部分(区别于 XHR 对象的 readystatechange 事件)提供了该事件,这个事件的目的是提供与文档或元素的加载状态有关的信息,但这个事件的行为有时候也很难预料。支持该事件的对象都有一个readyState属性,注意,不是 event 事件对象。IE、Firefox4+和Opera 支持该事件。
readyState属性的值如下:
“uninitialized” - 未初始化:对象存在但尚未初始化;
“loading” - 正在加载:对象正在加载数据;
“loaded” - 加载完毕,对象加载数据完毕;
“interactive” - 交互:可以操作对象了,但还没有完全加载;
“complete” - 完成:对象已经加载完成;
2.1、并非所有的对象都会经历readyState的这几个阶段,如果这个阶段不适用某个对象,则该对象完全可能跳过该阶段,并没有规定哪个阶段适用于哪个对象。这意味着 readystatechange 事件经常会少于4次,相对应的 readyState 属性值也不是连续的。
2.2、对于 document 而言,interactive 和 complete 阶段会在于 DOMContentLoaded 大致相同的时刻触发 readystatechange 事件;
load 事件和 readystatechange 事件的触发顺序会因页面的外部资源的多少而变化,也就是说,readystatechange 事件并不会一直在 load 事件之前执行。外部资源越多,对 readystatechange 事件就越有利。
interactive 和 complete 的顺序也是不一致的,谁都有可能先执行,引用的外部资源越多,对交互阶段越有利。所以为了尽可能早的执行代码,两个状态要同时判断。
3、doScroll
IE5.5+支持,当页面中有滚动条时,可以用 doScroll("right")/doScroll("down") 等来移动滚动条,这个方法只有等DOM加载完成以后才能用,所以在IE低版本浏览器中可以通过这个属性判断 DOM 结构是否加载完成。介绍这个属性主要是模仿 jquery 中的解决方案。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
|
注:
setTimeout(checkDoScroll, 1); 目的是让浏览器尽快执行 checkDoScroll 函数,间隔时间设置为 1ms,对当下的浏览器来说是不太可能的。每个浏览器都有自己默认的最小间隔时间,即使时间设置为最小间隔时间,也只是代表隔这些时间过去之后,JavaScript 会把 checkDoScroll 加入到执行队列中,如果此时 JavaScript 进程空闲,则会立即执行该代码。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
