本文共 2860 字,大约阅读时间需要 9 分钟。
ajax()
,使用时传递一个对象type
、请求地址url
、请求参数data
、请求参数格式的类型(字符串orjson
对象)、请求成功后的函数、请求失败后的函数等属性ajax({ // 请求方式 type: 'get', // 请求地址 url: 'http://localhost:3000/responseData', // 请求参数 data: { name: 'Jack', age: '20' }, // 格式类型 header: { 'Content-Type': 'application/json' }, // 请求成功后的函数 success: function(data, xhr) { console.log('这里是success函数'); console.log(data); }, // 请求失败后的函数 error: function(data, xhr) { console.log('这里是error函数' + data); console.log(xhr); }});
ajax()
内部有默认值。对于未传递的属性则使用默认值。// 存储默认值的对象var defaults = { type: 'get', url: '', data: { }, header: { 'Content-Type': 'application/x-www-form-urlencoded' }, success: function() { }, error: function() { }}
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.substr(0, params.length - 1); // console.log(params); // 判断请求方式 if (defaults.type == 'get') { defaults.url = defaults.url + '?' + params; } // 配置ajax对象 xhr.open(defaults.type, defaults.url); // 发送请求 if (defaults.type == 'post') { // 用户设置的向服务器端传递的请求参数类型 var contentType = defaults.header['Content-Type']; // 设置请求参数格式的类型 xhr.setRequestHeader('Content-Type', contentType); // 判断用户希望的请求参数格式类型 if (contentType === 'application/json') { // 如果类型为json,向服务器端传递json数据格式的参数 xhr.send(JSON.stringify(defaults.data)); } else { // 向服务器端传递普通类型的参数 xhr.send(params); } } else { xhr.send(); } // 监听xhr对象下面的onload事件 // xhr对象接收完响应数据后触发 xhr.onload = function() { // 获取响应头中的数据 var contentType = xhr.getResponseHeader('Content-Type'); // 服务器返回的数据 var responseText = xhr.responseText; 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); } }}
转载地址:http://odsu.baihongyu.com/