In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to master AJAX". In daily operation, I believe many people have doubts about how to master AJAX. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts of "how to master AJAX"! Next, please follow the editor to study!
What is ajax?
AJAX is a set of API provided by the browser, which can be called through JavaScript to control the request and response through code. Realize
Network programming
1. The process of using AJAX can be compared to the usual process of visiting a web page / / 1. Creating an object of type XMLHttpRequest is equivalent to opening a browser var xhr = new XMLHttpRequest () / / 2\. Opening a connection to a URL is equivalent to entering the access address xhr.open ('GET','. / time.php') / / 3\ in the address bar. Send a request through the connection-equivalent to enter or click to visit and send the request xhr.send (null) / / 4\. Specify the xhr state change event handler function-equivalent to the operation xhr.onreadystatechange = function () {/ / determine whether the response to this request has been received by the readyState of xhr (this.readyState = 4) {/ / get the response body console.log (this)} through the responseText of xhr}
I am an old code farmer who has been developed for several years. I hope this article will be useful to you! Here I recommend my front-end learning exchange circle: 767273102, which is all learning front-end, from the most basic HTML+CSS+JS [cool special effects, games, plug-in packaging, design patterns] to the actual combat learning materials of mobile HTML5 projects are sorted out and sent to every front-end partner. 2019 the latest technology, synchronized with the needs of the enterprise. Friends are inside to learn and communicate, every day there will be Daniel regularly explain the front-end technology!
2 、 readyState
Since the readystatechange event is triggered when the state of the xhr object changes (not just when the response is received), this means that the event will be
Triggered multiple times, so it is necessary to understand what each status value represents:
[failed to upload picture... (image-62c2e1-1558359068841)]
Timeline:
[failed to upload picture... (image-6e1d8d-1558359068841)]
Var xhr = new XMLHttpRequest () console.log (xhr.readyState) / / = > 0max / initialize the request proxy object xhr.open ('GET',' time.php') console.log (xhr.readyState) / / = > 1max / open method has been called Establish a connection to a server-specific port xhr.send () xhr.addEventListener ('readystatechange' Function () {switch (this.readyState) {case 2max / = > 2max / has received the response header of the response message / / can get the header / / console.log (this.getAllResponseHeaders ()) console.log (this.getResponseHeader ('server')) / / but has not yet got the body console.log (this.responseText) breakcase 3move / = > 3max / the response body that is downloading the response message It is possible that the response body is empty or incomplete / / it is not safe to deal with the response body here (unreliable) console.log (this.responseText) breakcase 4 OK / > 4 OK (the whole response message has been downloaded completely) / / the response body console.log (this.responseText) break}})
By understanding the meaning of each state value, we come to the conclusion that we generally execute the subsequent logic of the response when the readyState value is 4.
Xhr.onreadystatechange = function () {if (this.readyState = 4) {/ / subsequent logic.} 3, follow HTTP
In essence, XMLHttpRequest is the means by which JavaScript sends HTTP requests on the Web platform, so the request we send is still
HTTP request, which also conforms to the format of the HTTP convention:
/ / set the request line xhr.open ('GET','. / time.php') of the request message / / set the request header xhr.setRequestHeader ('Accept' 'text/plain') / / set request body xhr.send (null) xhr.onreadystatechange = function () {if (this.readyState = 4) {/ / get response status code console.log (this.status) / / get response status description console.log (this.statusText) / / get response header information console.log (this.getResponseHeader (' Content-Type')) / / specify response header console.log (this.getAllResponseHeader () ) / / all response headers / / get the response body console.log (this.responseText) / / text form console.log (this.responseXML) / / XML form If you understand it, you don't need it. 4. GET request
Usually during a GET request, the parameters are passed through the URL address. Parameters are passed.
Var xhr = new XMLHttpRequest () / / GET request pass parameters usually use question mark to pass parameters / / here you can add parameters after the request address to pass data to the server xhr.open ('GET','. / delete.php?id=1') / / generally, there is no need to set the response body during the GET request You can pass null or simply not xhr.send (null) xhr.onreadystatechange = function () {if (this.readyState = 4) {console.log (this.responseText)}} / / generally, URL transmits data of a parameter nature, while POST is usually a business data 5 or POST request.
In the process of POST request, the request body is used to carry the data to be submitted.
The first parameter of the var xhr = new XMLHttpRequest () / / open method sets the request's methodxhr.open ('POST','. / add.php') / / sets the Content-Type in the request header to application/x-www-form-urlencoded// to identify the request body format as urlencoded so that the server can receive the data xhr.setRequestHeader ('Content-Type'). 'application/x-www-form-urlencoded') / / data that needs to be submitted to the server can be passed through the parameters of the send method / / format: key1=value1&key2=value2xhr.send (' key1=value1&key2=value2') xhr.onreadystatechange = function () {if (this.readyState = 4) {console.log (this.responseText)}} 6. Synchronous and asynchronous synchronization: a person can only do one thing at a time Don't do anything else while performing some time-consuming operation (without care), just wait for asynchronism: perform some time-consuming operation (without care) to do something else, instead of waiting.
The third parameter of the xhr.open () method requires that a bool value be passed in, and its function is to set whether the request is executed asynchronously. Default
For true, if you need synchronous execution, you can do so by passing false:
Console.log ('before ajax') var xhr = new XMLHttpRequest () / / the default third parameter is true, which means that xhr.open (' GET','. / time.php', true) xhr.send (null) xhr.onreadystatechange = function () {if (this.readyState = 4) {/ / the code here finally executes console.log ('request done')} console.log (' after ajax')
If executed synchronously, the code will get stuck at the xhr.send () step:
Console.log ('before ajax') var xhr = new XMLHttpRequest () / / synchronous mode xhr.open (' GET','. / time.php', false) / / synchronous mode execution requires registering the event before calling send, otherwise readystatechange cannot trigger xhr.onreadystatechange = function () {if (this.readyState = 4) {/ / the code here finally executes console.log ('request done')} xhr.send (null) console.log (' after ajax')
Demonstrates synchronous and asynchronous differences.
Be sure to register readystatechange (whether synchronous or asynchronous) before sending the request send ()
In order to make this event more reliable (it must be triggered), you must register first.
Just understand synchronous mode, and remember not to use synchronous mode.
At this point, we have a general understanding of the basic API of AJAX.
7. Response data format
Question: what if you want the server to return a complex data?
The concern is what format the server sends out, and how this format is parsed with JavaScript on the client.
XML
A means of data description, basically the current project is not used, the reason for elimination: too much data redundancy.
JSON
It is also a means of data description, similar to the JavaScript literal method.
The server returns the data in JSON format, and the client parses the data in JSON format.
Whether it is JSON or XML, just because it is used in the AJAX request process does not mean that there is an inevitable connection between them, they just
Just a data protocol.
Compatible scheme
XMLHttpRequest has compatibility issues in older browsers (IE5/6) and can be replaced in another way
Var xhr = window.XMLHttpRequest? New XMLHttpRequest (): new ActiveXObject ('Microsoft.XMLHTTP') 8, encapsulation AJAX request encapsulation
The function can be understood as something you want to do, and the process of doing it is specified in the function body, and it doesn't start to work until it is called.
Passing a function as an argument is like handing over a thing to someone else. This is the concept of delegation.
/ * send an AJAX request * @ param {String} method request method * @ param {String} url request address * @ param {Object} params request parameters * @ param {Function} what needs to be done after the request is completed (delegate / callback) * / function ajax (method, url, params Done) {/ / uniform conversion to uppercase facilitates subsequent judgment that parameters in the form of method = method.toUpperCase () / / object are converted to urlencoded format var pairs = [] for (var key in params) {pairs.push (key +'='+ params [key])} var querystring = pairs.join ('&') var xhr = window.XMLHttpRequest? New XMLHttpRequest (): newActiveXObject ('Microsoft.XMLHTTP') xhr.addEventListener (' readystatechange', function () {if (this.readyState! = = 4) return// attempts to parse the responder try {done (JSON.parse (this.responseText))} catch (e) {done (this.responseText)}) / / if it is a GET request, set the URL address question mark parameter if (method = 'GET') {url + ='?'+ querystring} xhr.open (method) Url) / / if it is a POST request, set the request body var data = nullif (method = = 'POST') {xhr.setRequestHeader (' Content-Type', 'application/x-www-form-urlencoded') data = querystring} xhr.send (data)} ajax (' get','. / get.php', {id: 123}, function (data) {console.log (data)}) ajax ('post','. / post.php', {foo: 'posted data'}) Function (data) {console.log (data)}) 9, AJAX$.ajax$.ajax in jQuery ({url:'. / get.php',type: 'get',dataType:' json',data: {id: 1}, beforeSend: function (xhr) {console.log ('before send')}, success: function (data) {console.log (data)}, error: function (err) {console.log (err)}, complete: function {console.log (' request completed')}})
Introduction to common options and parameters:
Url: request address type: request method Default is getdataType: server response data type ajax ('get','. / get.php', {id: 123}, function (data) {console.log (data)}) ajax ('post','. / post.php', {foo: 'posted data'}, function (data) {console.log (data)}) $.ajax ({url:' / get.php',type: 'get',dataType:' json',data: {id: 1} BeforeSend: function (xhr) {console.log ('before send')}, success: function (data) {console.log (data)}, error: function (err) {console.log (err)}, complete: function () {console.log (' request completed')}})
Introduction to common options and parameters:
Url: request address
Type: request method. Default is get.
DataType: server response data type
ContentType: request body content type. Default is application/x-www-form-urlencoded.
Data: the data that needs to be passed to the server, if GET is passed through URL, if POST is passed through the request body
Timeout: request timeout
BeforeSend: triggered before the request is initiated
Success: triggered after a successful request (response status code 200)
Error: triggered by a failed request
Complete: request completion trigger (whether successful or not)
10. Cross-domain
Related concepts
The same origin policy is a security policy of the browser. The so-called "same origin" means that the domain name, protocol and port are exactly the same. Only addresses of the same origin can pass through each other.
Request in the form of AJAX.
The same origin or different origin refers to the relationship between two addresses. Requests between different source addresses are called cross-domain requests.
What is homology? For example: http://www.example.com/detail... Compare with the address below
JSONP
JSON with Padding is a technique for sending cross-domain requests with the help of script tags.
The principle is to request a dynamic web page (php file) on the server side with the help of script tags on the client side, and the dynamic web page on the server side returns a
A script for a JavaScript global function call with a function call that passes in the data that would otherwise have been returned to the client.
In the future, in most cases, JSONP is used to complete cross-domain requests between different source addresses.
Foo (['I', 'yes', 'you', 'Ben', 'need', 'want', 'number', 'data') this is the end of the study on "how to master AJAX", hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.