Related learning recommendations: ajax
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 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.
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); } })复制代码
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); } })复制代码
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.
This is the final version of the code, there will be targeted explanations behind the code.
var defaults = { type: 'get', url: '', data: {}, header: { 'Content-Type': 'application/x-www-form-urlencoded' }, success: function () {}, error: function () {} }; // 使用options对象中的属性覆盖defaults对象中的属性 Object.assign(defaults, options);复制代码
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 }复制代码
// 创建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);复制代码
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(); }复制代码
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); } } }复制代码
完整的封装代码贴出来,如下所示:
<script type="text/javascript"> function ajax (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); // 创建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); // 判断请求方式 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(); } // 监听xhr对象下面的onload事件 // 当xhr对象接收完响应数据后触发 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); } } } ajax({ type: 'post', // 请求地址 url: 'http://localhost:3000/responseData', success: function (data) { console.log('这里是success函数'); console.log(data) } }) </script>复制代码
ok,到此封装ajax函数完毕,为什么要封装,减少使用多个ajax请求的时候代码冗余。把代码用函数封装起来使用的时候调用函数就可。封装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!