What is the AJAX

Async javascript and XML: Asynchronous JS and XML

  • By asynchrony, WE mean: local refresh (global refresh)
  • XML: Extensible markup language that stores data with its own custom tags. (In the early days, the data format that we used to interact with the server based on AJAX was mostly XML, because it clearly showed the corresponding data and structure hierarchy. But later, a new data format, JSON, is popular, which not only shows the data structure more clearly than XML, but also the same data storage, JSON is lighter, and convenient for parsing and related operations, so now the front and back end of the data interaction is mainly JSON format.)
<? xml version="1.0" encoding="UTF-8"? ><root>
<student>
<name>Zhang SAN</name>
<age>25</age>
<score>
<english>95</english>
</score>
</student>
<student>
<name>Zhang SAN</name>
<age>25</age>
</student>
<student>
<name>Zhang SAN</name>
<age>25</age>
</student>
</root>-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- [{"name": "Zhang"."age": 25."score": {
"english": 95}}, {"name": "Zhang"."age": 25
}, {
"name": "Zhang"."age": 25
}]
Copy the code
  • AJAX solves the problem of asynchronous page refreshes

AJAX basics

//1. Create AJAX instances
let xhr=new XMLHttpRequest; //=>IE low version browser using new ActiveXObject() elevation 3 JS inert programming ideas, about XHR compatible processing

//2. Open the URL (configure the information to send the request)
//METHOD: indicates the HTTP request mode
//URL: request address (API interface address)
//ASYNC: Sets ASYNC or ASYNC. The default is TRUE ASYNC and FALSE ASYNC
// user-name: indicates the USER NAME passed to the server
// user-pass: password passed to the server
xhr.open('GET'.'./json/xxx.json'.true);

//3. Listen for AJAX state and get the content of the server response when state is X
//AJAX status code: 0 1 2 3 4
xhr.onreadystatechange=function(){
   if(xhr.readyState===4 && /^(2|3)\d{2}$/.test(xhr.status)){
      letresult = xhr.responseText; }}//4. Send request
//SEND puts the contents of the request body
xhr.send(null); =>AJAX tasks (sending a request to the server and getting the corresponding content from the server) start after SEND and go to xhr. READYSTATE===4The mission is overCopy the code

HTTP request mode

  • GET series of requests
    • GET
    • DELETE is usually used to tell the server to DELETE something from the server
    • The HEAD only wants to fetch the response header content, telling the server that the response body content is no longer needed
    • OPTIONS test request, send a request to the server, see if the server can receive, can return
  • POST Series requests
    • POST
    • PUT, as opposed to DELETE, usually wants the server to store the information I pass to the server (usually applies to files and large data contents).

=> Use the corresponding request methods in real projects to make the request more explicit (semantic), do not follow these methods, at least the browser syntax is allowed; But these are norms that developers have agreed to with each other;

What’s the difference between get and Post?

The GET series is generally used to GET information from the server, and the POST series is generally used to push information to the server. However, both GET and POST can transmit information to the server and obtain results from the server. It is just a matter of who is more or less

  • GET: Give little, take much
  • POST: Give more, take less
How does the client pass information to the server?
  • Xhr. open(‘GET’,’/ getData? xxx=xxx&xxx=xxx’)
  • Set the request header xhr.setrequestheader ([key],[value])
  • Set request body xhr.send(request body information)
How does the server return information to the client?
  • Through the response header
  • Through the response body (on which most of the information is returned)
Essential differences between the GET series and the POST series:

The GET series transmits information to the server in the following way: Question mark (?) parameter Transfer POST series transmits information to the server in the following way: Set the request body

  1. GET sends less content to the server than POST because the URL has a maximum size limit (IE typically limits 2KB, Google typically limits 4-8KB, and the browser automatically intercepts any portion that exceeds the length).
xhr.open('GET'.'/list? name=zhufeng&year=10&xxx=xxx... ')
xhr.send('....'In theory, there is no size limit to what can be passed in the request body, but in real projects, we limit it ourselves to ensure the speed of the transferCopy the code
  1. GET creates caching (which is out of your control) : Because of the address requested (especially the question mark), browsers sometimes assume that you want to retrieve the same information as they did last time; We don’t expect this cache, we expect the cache to be self-controlled; So in a real project, if we GET multiple requests to an address, we want to remove the cache;
//=> Solution set random number xhr.open('GET'.'/list? name=zhufeng&_='+Math.random()); . xhr.open('GET'.'/list? name=zhufeng&_='+Math.random());
Copy the code
  1. Compared with POST, GET is not secure. GET is the content transmitted to the server based on question mark parameters. There is a technology called URL hijacking, so that others can obtain or tamper with the information transmitted. POST, on the other hand, transmits information based on the subject of the request and is not easy to be hijacked.

AJAX status code

Xhr. readyState Obtains the status code

  • UNSEND 0: not sent (create an XHR, initial state 0)
  • OPENED: OPENED (xhr.open)
  • HEADERS_RECEIVED 2: The response header information has been returned to the client (after sending the request, the server will return the response header and the response body information in turn)
  • LOADING 3: Waits for the server to return a response
  • DONE 4: Response body information has been returned to the client
<script>
		 let xhr = new XMLHttpRequest;
		// console.log(xhr.readyState); / / = > 0
		xhr.open('GET'.'json/data.json');
		// console.log(xhr.readyState); / / = > 1
		xhr.onreadystatechange = function () {
			// console.log(xhr.readyState); / / = > 2, 3, 4
			if (!/^(2|3)\d{2}$/.test(xhr.status)) return;
			if (xhr.readyState === 2) {
				//=> Obtain response header information
				// The server time obtained is the standard date format object (GMT GMT)
				// New Date() converts Greenwich to Beijing time
				let serverTime = xhr.getResponseHeader('Date');
				// console.log(new Date(serverTime));
			}
			if (xhr.readyState === 4) {
				ResponseText => responseText => responseText => responseText => responseText;
				// xhr.responseXML
				// xhr.response
				// xhr.responseType
				// console.log(xhr.responseText);
			}
		}
		xhr.send(null); 
	</script>
Copy the code

Synchronous asynchronous

<script> //=> Asynchronous let XHR for AJAX tasks = new XMLHttpRequest; xhr.open('GET', 'json/data.json'); Xhr.onreadystatechange = function () {console.log(xhr.readyState); //=>2 3 4 } xhr.send(null); let xhr = new XMLHttpRequest; xhr.open('GET', 'json/data.json'); xhr.send(null); xhr.onreadystatechange = function () { console.log(xhr.readyState); //=>AJAX synchronization /**/ let XHR = new XMLHttpRequest; xhr.open('GET', 'json/data.json', false); xhr.onreadystatechange = function () { console.log(xhr.readyState); } xhr.send(null);} xhr.send(null);} xhr.send(null);} xhr.send(null); let xhr = new XMLHttpRequest; xhr.open('GET', 'json/data.json', false); xhr.send(null); // if the status code is 4, the following code will continue to be processed. Xhr.onreadystatechange = function () {console.log(xhr.readystate); </script> </script> </script>Copy the code
<script>
		 let xhr = new XMLHttpRequest;
		// xhr.timeout = 10; //=> Set the AJAX wait time, which counts as AJAX delay
		// xhr.ontimeout = function () {
		// console.log(' Request timed out ~~');
		// xhr.abort(); //=> Manually interrupt the AJAX request
		// }
		// xhr.withCredentials = true; //=> Whether certificates (with cookies) are allowed in cross-domain requests
		xhr.open('GET'.'json/data.json');
		//=> Set the request header
		Xhr.setrequestheader ('AAA', encodeURIComponent(' Everest Training ')); // xhr.setrequestheader ('AAA', encodeURIComponent(' Everest training '));
		// Uncaught TypeError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': Value is not a valid ByteString. The value of the request header cannot be Chinese
		xhr.onreadystatechange = function () {
			if (!/^(2|3)\d{2}$/.test(xhr.status)) return;
			if (xhr.readyState === 4) {
				console.log(xhr.responseText);//-> {"code":63732359.6050773,"data":[{"name":"laborum velit rederit et adipisicing"},{"name":"sed occaecat ", dolore"}]}
			}
		}
		xhr.send(null);
	</script>
Copy the code

AJAX synchronization issues

Block code addition

Delayed loading time and low performance

Summarize XHR properties and methods and events

【 property 】

  • Xhr. response Indicates the response body

  • Xhr.responsetext The content of the response body is a string (either in JSON or XML format)

  • Xhr.responsexml The contents of the response body are XML documents

  • Xhr. status HTTP status code returned

  • Xhr. statusText Description of the status code

  • Xhr. timeout Sets the timeout period of the request

  • Xhr.withcredentials Whether certificates are allowed in cross-domain requests (with cookies)

【 method 】

  • Xhr.abort () forces the interruption of an AJAX request
  • XHR. The getAllResponseHeaders () to get all the response header information
  • Xhr.getresponseheader ([key]) Obtains the response header information corresponding to the key
    • For example: xhr.getresponseheader (‘date’) is the server time in getting the response
  • Xhr.open () opens the URL request
  • Xhr.overridemimetype () overrides the MIME type
  • Xhr.send () sends AJAX requests
  • Xhr.setrequestheader () sets the request header

Ajax in JQUERY

<script src="js/jquery.min.js"></script>
	<script>
		/* * $.ajax() based on the native JS ajax four-step operation to wrap * $.ajax([URL],[OPTIONS]) * $.ajax([OPTIONS]) URL in the configuration item (recommended) * $.get/post/getJSON/getScript() * ...... Method :HTTP request method, default GET * data: information passed to the server, default null (can be a string, can be an object, and if GET series of requests, JQ will automatically concatenate information to the end of the URL, Pass to the server based on question mark pass parameter; If it is a POST request, JQ will pass the information to the server based on the request body.) * dataType: Default format of the result returned by the server (the server usually returns a STRING in JSON format. If data-type is set, JQ will specify the TYPE, Text/json/XML/HTML/script/jSONp (cross-domain) => Does not affect the result returned by the server, only the result returned by the server for secondary processing The default value is TRUE, indicating asynchronous operation * cache: cache processing, only for GET series of requests, the default value is TRUE, does not handle cache, when we set FALSE, JQ sets a random number at the end of the URL * contentType: Sets the format type of the content to be passed to the server. Default is "Application/X-www-form-urlencoded" * The format of the information that the client will pass to the server (usually a string). Commonly used: * form - the data form data: JSON format '{" name ":" XXX, "" lx" : 1}' * x - WWW - form - urlencoded: name = xxx&lx = 1 * raw: * timeout: specifies the timeout period. * Success: specifies a callback function. If the data request is successfully executed, the parameters in the method are the result obtained from the server. The argument in the method is an error message */
		$.ajax({
			url: 'http://yapi.demo.qunar.com/mock/95100/project/list'.method: 'POST'.data: {
				name: 'zhufeng'.lx: 'teacher'
			},
			dataType: 'json'.async: true.cache: false.headers: {},
			success: (result, status, xhr) = > {
				//=> XHR: is an AJAX instance that JQ has handled for us
				console.log(result, status, xhr); }});</script>
Copy the code