Home > Web Front-end > JS Tutorial > body text

Understand Ajax encapsulation

coldplay.xixi
Release: 2020-09-19 17:01:09
forward
1794 people have browsed it

Understand Ajax encapsulation

Related learning recommendations: ajax

Preface

The previous article talked about the principle, function and implementation of ajax. But they only implement an ajax request and response operation. There will not be only one request and response between the browser and the server. If you add 100 requests and responses, do you need to write similar code 100 times?

This article is to solve the problem of how to send multiple ajax. If you don't know ajax, read my last article "Understanding ajax" carefully. You can get the content of this article in about 5 minutes.

This article actually talks about a function. Let’s take a look next.

The idea of ​​encapsulation

The operations of sending multiple requests are the same. If you write multiple requests, there will be duplicate code. To avoid code redundancy, you can use the idea of ​​​​functions to encapsulate the ajax operation code into a function. The parameters passed by different request functions are all different. If you want to send ajax requests multiple times, just call our encapsulated function.

Basic implementation of ajax function encapsulation

As mentioned earlier, using functions to encapsulate ajax, then the four steps of ajax implementation are put into the function, and then the function is called. Because there are more parameters passed, the parameters Represented by an object options. This object includes the request method, request address, and the request processing function triggered after the request is sent successfully.

Let’s take a look at the example below. In the code, the ajax operation is encapsulated into the ajax function, the ajax function is called, and the parameters are passed in. After the onload event under xht is triggered, the success function is called and the corresponding content xhr.responsetext is printed 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 after login

Encapsulation of request parameters

The above code implements basic encapsulation. Next, let’s talk about how to encapsulate request parameters. The post method and get method were introduced in the previous article. Two methods are used to send requests. The request parameters of different request methods are also placed in different locations. For example, the get method is spliced ​​after the url, and the post method is placed in the send method. We add a data attribute to the actual parameter object of the ajax method, and the value of the data attribute is the request parameter.

Use the for-in loop to splice the request parameters in the ajax function, and remove the redundant & in the request parameters. Then make a judgment on the request type. If it is a get request, just splice the params just spliced ​​behind the url; if it is a post request, put the parameters in the send method, and use the setRequestHeader method under the xhr object to set the request parameter format. type.

The code is as follows:

	var xhr = new XMLHttpRequest();
	// 拼接请求参数的变量
	var params = '';
	// 循环用户传递进来的对象格式参数	for (var attr in options.data) {
		// 将参数转换为字符串格式
		params += attr + '=' + options.data[attr] + '&';
	}
	// 将参数最后面的&截取掉 
	// 将截取的结果重新赋值给params变量
	params = params.substr(0, params.length - 1);

	// 判断请求方式	if (options.type == 'get') {
		options.url = options.url + '?' + params;
	}


	// 配置ajax对象
	xhr.open(options.type,options.url);
	// 如果请求方式为post	if (options.type == 'post') {
		// 设置请求参数格式的类型
		xhr.setRequestHeader('Content-Type', contentType);
    	// 向服务器端传递请求参数
		xhr.send(params);
		
	}else {
		// 发送请求
		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 after login

Encapsulated Ultimate Version

After entering the first two warm-ups, look directly at the final version of the ajax package. The Ultimate Edition package solves the following problems.

  • Processing of the data format returned by the server
  • Processing of the browser request parameter format
  • The status code is not 200 and the call failure function
  • Set the default parameters Reduce redundancy

This is the final version of the code, there will be targeted explanations behind the code.

Analysis of the ultimate version code:

Set default parameters to reduce redundancy

  1. Set the defaults parameter object in the ajax function. Why do we need to add default parameters to the function when we pass in parameters when calling the ajax function? In the final analysis, it is to avoid code redundancy. If multiple ajax objects are created, the same parameters may be passed in. We only Pass in specific parameter options when calling, and let the options override the default parameters defaults. Using defaults inside the function can perfectly solve this problem. Object.assign(defaults, options) is to let defaults override options.
	var defaults = {			type: 'get',
			url: '',
			data: {},
			header: {				'Content-Type': 'application/x-www-form-urlencoded'
				},
			success: function () {},
			error: function () {}
		};
		// 使用options对象中的属性覆盖defaults对象中的属性
		Object.assign(defaults, options);复制代码
Copy after login

Object.assign method

Supplementary:Object.assign method

Here is a code that is enough for this article, specifically For more in-depth information, please read the official documentation

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 after login

创建ajax对象,拼接请求参数

		// 创建ajax对象
		var xhr = new XMLHttpRequest();
		// 拼接请求参数的变量
		var params = '';
		// 循环用户传递进来的对象格式参数		for (var attr in defaults.data) {
				// 将参数转换为字符串格式
				params += attr + '=' + defaults.data[attr] + '&';
			}
		// 将参数最后面的&截取掉 
		// 将截取的结果重新赋值给params变量
		params = params.substr(0, params.length - 1);复制代码
Copy after login

浏览器请求参数格式的处理

  1. 判断请求方式是get合适post。如果是get就将请求参数拼接到请求地址后面,再配置ajax对象,用send方法发送请求;如果是post就先配置ajax对象,然后判断请求参数的数据类型,如果是json类型就把数据类型转换成字符串处理,如果是application/x-www-form-urlencoded就直用send方法向服务器传递普通请求参数发送请求。
		if (defaults.type == 'get') {
				defaults.url = defaults.url + '?' + params;
			}
		// 配置ajax对象
		xhr.open(defaults.type, defaults.url);
		// 如果请求方式为post		if (defaults.type == 'post') {
				// 用户希望的向服务器端传递的请求参数的类型
				var contentType = defaults.header['Content-Type']
				// 设置请求参数格式的类型
				xhr.setRequestHeader('Content-Type', contentType);
				// 判断用户希望的请求参数格式的类型
				// 如果类型为json				if (contentType == 'application/json') {
					// 向服务器端传递json数据格式的参数
					xhr.send(JSON.stringify(defaults.data))
				}else {
					// 向服务器端传递普通类型的请求参数
					xhr.send(params);
				}

			}else {
			// 发送请求
			xhr.send();
		}复制代码
Copy after login

服务器返回数据格式的处理

4.当请求发送成功,就会触发onload事件,执行函数。我们要对服务器响应的数据进行格式判断,用getResponseHeader方法获取响应头的数据,Content-Type是响应头的属性名称。如果响应头中包含application/json这个字符,就说明响应的是json对象,但是传输的时候是字符串形式传输,所以用json下的parse方法转字符串为对象。 如果http的状态码是200就说明客户端发来的请求在服务器端得到了正确的处理。调用success函数,否则调用错伏处理函数。

		xhr.onload = function () {
			// xhr.getResponseHeader()
			// 获取响应头中的数据
			var contentType = xhr.getResponseHeader('Content-Type');
			// 服务器端返回的数据
			var responseText = xhr.responseText;
			// 如果响应类型中包含applicaition/json			if (contentType.includes('application/json')) {
				// 将json字符串转换为json对象
				responseText = JSON.parse(responseText)
			}
			// 当http状态码等于200的时候			if (xhr.status == 200) {
				// 请求成功 调用处理成功情况的函数
				defaults.success(responseText, xhr);
			}else {
				// 请求失败 调用处理失败情况的函数
				defaults.error(responseText, xhr);
			}
		}
	}复制代码
Copy after login

完整的封装代码贴出来,如下所示:

<script type="text/javascript">	function ajax (options) {
		// 存储的是默认值
		var defaults = {			type: &#39;get&#39;,
			url: &#39;&#39;,
			data: {},
			header: {				&#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded&#39;
				},
			success: function () {},
			error: function () {}
		};
		// 使用options对象中的属性覆盖defaults对象中的属性
		Object.assign(defaults, options);
		// 创建ajax对象
		var xhr = new XMLHttpRequest();
		// 拼接请求参数的变量
		var params = &#39;&#39;;
		// 循环用户传递进来的对象格式参数		for (var attr in defaults.data) {
				// 将参数转换为字符串格式
				params += attr + &#39;=&#39; + defaults.data[attr] + &#39;&&#39;;
			}
		// 将参数最后面的&截取掉 
		// 将截取的结果重新赋值给params变量
		params = params.substr(0, params.length - 1);
		// 判断请求方式		if (defaults.type == &#39;get&#39;) {
				defaults.url = defaults.url + &#39;?&#39; + params;
			}
		// 配置ajax对象
		xhr.open(defaults.type, defaults.url);
		// 如果请求方式为post		if (defaults.type == &#39;post&#39;) {
				// 用户希望的向服务器端传递的请求参数的类型
				var contentType = defaults.header[&#39;Content-Type&#39;]
				// 设置请求参数格式的类型
				xhr.setRequestHeader(&#39;Content-Type&#39;, contentType);
				// 判断用户希望的请求参数格式的类型
				// 如果类型为json				if (contentType == &#39;application/json&#39;) {
					// 向服务器端传递json数据格式的参数
					xhr.send(JSON.stringify(defaults.data))
				}else {
					// 向服务器端传递普通类型的请求参数
					xhr.send(params);
				}

			}else {
			// 发送请求
			xhr.send();
		}
		// 监听xhr对象下面的onload事件
		// 当xhr对象接收完响应数据后触发
		xhr.onload = function () {
			// xhr.getResponseHeader()
			// 获取响应头中的数据
			var contentType = xhr.getResponseHeader(&#39;Content-Type&#39;);
			// 服务器端返回的数据
			var responseText = xhr.responseText;
			// 如果响应类型中包含applicaition/json			if (contentType.includes(&#39;application/json&#39;)) {
				// 将json字符串转换为json对象
				responseText = JSON.parse(responseText)
			}
			// 当http状态码等于200的时候			if (xhr.status == 200) {
				// 请求成功 调用处理成功情况的函数
				defaults.success(responseText, xhr);
			}else {
				// 请求失败 调用处理失败情况的函数
				defaults.error(responseText, xhr);
			}
		}
	}
	ajax({		type: &#39;post&#39;,
		// 请求地址
		url: &#39;http://localhost:3000/responseData&#39;,
		success: function (data) {
			console.log(&#39;这里是success函数&#39;);
			console.log(data)
		}
	})
</script>复制代码
Copy after login

文章结束

ok,到此封装ajax函数完毕,为什么要封装,减少使用多个ajax请求的时候代码冗余。把代码用函数封装起来使用的时候调用函数就可。封装ajax函数要考虑到以下几点:

  • 请求方式(get),请求参数要与地址拼接后放到open方法中。
  • 请求方式post,请求参数类型是json数据类型,要将json转字符串后放到send方法中。
  • 对服务器响应处理时获取响应头中的响应数据格式。
  • 响应的格式是json对象,处理响应结果要将字符串转json对象。
  • 设置ajax函数的默认参数减少代码冗余。

其他相关学习推荐:javascript

The above is the detailed content of Understand Ajax encapsulation. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.im
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template