preface

The previous article covered the principles, functions, and implementation of Ajax. However, it is only an Ajax request response operation, the browser and the server will not only have one request response, add the request response 100 times, so you need to write 100 times similar code?

This article addresses the problem of sending multiple Ajax messages. If you are not familiar with Ajax, take a good look at my previous article hello, Ajax, and it will take you about 5 minutes to get to this article.

This article is really about a function. Let’s take a look.

Encapsulated idea

The operation of sending multiple requests is the same, and if you write more than one, you will have duplicate code. To avoid code redundancy, you can use the idea of functions to encapsulate the code for Ajax operations into a single function, where different requesting functions pass different parameters. If you want to send ajax requests more than once, just call our wrapped function.

Basic implementation of Ajax function encapsulation

If you use a function to encapsulate Ajax, you can put the four steps of ajax implementation into the function and then call the function. Since many parameters are passed, the parameters are represented by an object, Options. This object contains the request mode, the request address, and the request handler that is triggered when the request is successfully sent.

Let’s take a look at the following example. The code wraps the Ajax operation in an Ajax function, calls the Ajax function, passes in the parameters, and after the onload event under XHT is triggered, calls the Sunccess function and prints the corresponding content xhr.responseText to the console.

function ajax(options) {
    var xhr = new XMLHttpRequest();
    xhr.open(options.type, options.url);
    xhr.send();
    xhr.onload = function () {
        options.success(xhr.responsetext);
    }
}
ajax({ 
     type: 'get',
     url: 'http://www.example.com',
     success: function(data) { console.log(data); }})Copy the code

Encapsulation of request parameters

The above code to achieve the basic package, then talk about how to encapsulate the request parameters, post method are introduced in the previous article and the get method sends the request, the two methods has different way to request parameter is placed in different positions, such as the get method after splicing in the url, post method on the send method. We add a data property to the argument object of the Ajax method, and the value of the data property is the request parameter.

The ajax function uses a for-in loop to concatenate the request parameters, removing the superfluous & from the request parameters. Then judge the request type. If it is a GET request, concatenate the newly concatenated params to the url. If it is a POST request put the parameters into the SEND method and set the type of the request parameter format using the setRequestHeader method under the XHR object.

The code is as follows:

var xhr = new XMLHttpRequest(); // Concatenate the variable of the request parameter var params =' '; // Loop over the object format parameters passed in by the userfor (var attr inOptions. data) {// Convert arguments to string format params += attr +'=' + options.data[attr] + '&'; } params = params.substr(0, params.length-1); // Determine the request typeif (options.type == 'get') {
		options.url = options.url + '? '+ params; } // Configure the Ajax object xhr.open(options.type,options.url); // If the request is POSTif (options.type == 'post') {// Set the type of the request parameter format xhr.setrequesTheader ('Content-Type', contentType); // Pass the request parameter xhr.send(params) to the server; }else{// send the request xhr.send(); } xhr.onload =function () {
        options.success(xhr.responsetext);
        }
        
  ajax({ 
     type: 'get',
     url: 'http://www.example.com',
     data: {
         name:'linglong',
         age:20
     },
     success: function(data) { console.log(data); }})Copy the code

Packaged Ultimate edition

Go straight to the final version of the Ajax wrapper after the first two warm-up sessions. The Ultimate edition package addresses several issues.

  • The server returns data format processing
  • Browser request parameter formatting processing
  • Status code is not 200 call failed function
  • Set default parameters to reduce redundancy

This is the ultimate version of the code, the code will be explained.

Analysis of the ultimate code:

Set default parameters to reduce redundancy

  1. Set the defaults parameter object in the Ajax function. If we create multiple Ajax objects, we will pass in the same parameters. We will only pass in the specific parameter options when we call the function. Let options override the defaults argument. Using defaults inside functions solves this problem perfectly. Assign (defaults, options) ¶ Object.assign(defaults, options) ¶
	var defaults = {
			type: 'get',
			url: ' ',
			data: {},
			header: {
				'Content-Type': 'application/x-www-form-urlencoded'
				},
			success: function () {},
			error: function() {}}; // Override the attribute object. assign(defaults, options) in the defaults Object with the attributes in the options Object;Copy the code

Object. The assign method

Add: object.assign method

Here’s a code for this article, but look at the official documentation for more details

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }

Copy the code

Create an Ajax object to concatenate the request parameters

Var XHR = new XMLHttpRequest(); // Concatenate the variable of the request parameter var params =' '; // Loop over the object format parameters passed in by the userfor (var attr inDefaults.data) {// Convert arguments to string format params += attr +'=' + defaults.data[attr] + '&'; } params = params.substr(0, params.length-1);Copy the code

Browser request parameter formatting processing

  1. Determine the request type is get appropriate POST. If it is GET, the request parameters are concatenated to the request address, and then the Ajax object is configured to send the request. If it is POST, ajax objects will be configured first, and then the data type of request parameters will be judged; if it is JSON, the data type will be converted to string processing; if it is Application/X-www-form-urlencoded, ordinary request parameters will be transmitted to the server and requests will be sent by send method.
		if (defaults.type == 'get') {
				defaults.url = defaults.url + '? '+ params; } // Configure the Ajax object xhr.open(defaults.type, defaults.url); // If the request is POSTif (defaults.type == 'post'Var contentType = defaults.header[var contentType = defaults.header['Content-Type'] // Set the request parameter format type xhr.setrequestheader ('Content-Type', contentType); // Determine the type of request parameter format the user wants // if the type is JSONif (contentType == 'application/json') {// Pass xhr.send(json.stringify (defaults.data))}else{// Pass the normal request parameter xhr.send(params) to the server; }}else{// send the request xhr.send(); }Copy the code

The server returns data format processing

4. When the request is successfully sent, the onLoad event is triggered to execute the function. We need to judge the format of the data in the server response, and use the getResponseHeader method to get the data in the response header. The Content-Type is the attribute name of the response header. If the response header contains the application/json character, it indicates that the response is a JSON object. However, the string is transmitted as a string. Therefore, the JSON parse method is used to convert the string into an object. If the HTTP status code is 200, the request from the client is properly processed on the server. Call the SUCCESS function, otherwise call the fault volt handler.

		xhr.onload = functionVar contentType = xhr.getresponseHeader () {// xhr.getresponseHeader ();'Content-Type'); Var responseText = xhr.responseText; // If the response type contains applicaition/jsonif (contentType.includes('application/json'Parse () {responseText = json.parse (responseText)} // When the HTTP status code equals 200if(xhr.status == 200) {// Call defaults.success(responseText, XHR); }else{// call defaults.error(responseText, XHR); }}}Copy the code

The complete wrapper code is posted as follows:

<script type="text/javascript">
	functionAjax (options) {// Store default values var defaults = {type: 'get',
			url: ' ',
			data: {},
			header: {
				'Content-Type': 'application/x-www-form-urlencoded'
				},
			success: function () {},
			error: function() {}}; // Override the attribute object. assign(defaults, options) in the defaults Object with the attributes in the options Object; Var XHR = new XMLHttpRequest(); // Concatenate the variable of the request parameter var params =' '; // Loop over the object format parameters passed in by the userfor (var attr inDefaults.data) {// Convert arguments to string format params += attr +'=' + defaults.data[attr] + '&'; } params = params.substr(0, params.length-1); // Determine the request typeif (defaults.type == 'get') {
				defaults.url = defaults.url + '? '+ params; } // Configure the Ajax object xhr.open(defaults.type, defaults.url); // If the request is POSTif (defaults.type == 'post'Var contentType = defaults.header[var contentType = defaults.header['Content-Type'] // Set the request parameter format type xhr.setrequestheader ('Content-Type', contentType); // Determine the type of request parameter format the user wants // if the type is JSONif (contentType == 'application/json') {// Pass xhr.send(json.stringify (defaults.data))}else{// Pass the normal request parameter xhr.send(params) to the server; }}else{// send the request xhr.send(); } // listen for the onload event under the XHR object // trigger xhr.onload = when the XHR object receives the response datafunctionVar contentType = xhr.getresponseHeader () {// xhr.getresponseHeader ();'Content-Type'); Var responseText = xhr.responseText; // If the response type contains applicaition/jsonif (contentType.includes('application/json'Parse () {responseText = json.parse (responseText)} // When the HTTP status code equals 200if(xhr.status == 200) {// Call defaults.success(responseText, XHR); }else{// call defaults.error(responseText, XHR); } } } ajax({type: 'post'// Request url:'http://localhost:3000/responseData',
		success: function (data) {
			console.log('Here is the success function');
			console.log(data)
		}
	})
</script>
Copy the code

End of the article

Ok, this is the end of wrapping ajax functions, why to wrap, reduce the use of multiple Ajax requests code redundancy. Call the function when you use the code wrapped in a function. Encapsulating Ajax functions takes the following into account:

  • Request method (GET), the request parameters are concatenated with the address and placed in the open method.
  • The request mode is POST, and the request parameter type is JSON data type. You need to convert JSON to a string and put it in the SEND method.
  • Gets the format of the response data in the response header when processing the server response.
  • The format of the response is a JSON object, and the result is processed by converting the string to a JSON object.
  • Setting default parameters for Ajax functions reduces code redundancy.

Recently like crayon xiao Xin, stupid meng stupid meng.

Recommend to see hey hey hey.

See you in the next article, pen refill…..