前言:会调用是必须的,然后在会调用基础上懂得原理
结构分析:前端 后端 数据库调用
确定一下使用的方式
// 使用的时候直接调用,传递一个对象就可以
ajax({
url: '', // 请求的地址
type: '', // 请求方式
async: '', // 是否异步
data: '', // 携带的参数
dataType: '', // 要不要执行
json.parse success: function () {} // 成功以后执行的函数
})
btn.onclick = function (){
ajax({
url: './data/test4.php',
type: 'get',
// data: 'tt=123&abc=hehe&www=baidu',// 传字符串形式的参数⭐⭐⭐
data: {//传对象⭐⭐⭐
tt: '123',
abc: 'hehe',
www: 'baidu'
},
dataType: 'json', // 返回的数据类型 text json xml
cache: true,// 是否使用缓存,默认为false
success: function (json){
console.log(json.msg)
},
error: function (code){
console.log(code)
}
})
}
//判断是否对象
function isObject(obj){
if (Object.prototype.toString.call(obj) === '[object Object]') {
return true
}
return false
}
function ajax(options){
// data -> 'key=value&key=value' 。
// 1.创建数据交互对象
if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest() // 非IE5 6
} else {
var xhr = new ActiveXObject('Microsoft.XMLHTTP') // IE5 6
}
// 判断并格式化参数data
var data = ''
// if (typeof options.data === 'object' && options.data !== null && options.data.constructor === 'Object') {
if (isObject(options.data)) {
// 把对象格式化成 -> 'k1=v1&k2=v2&k3=v3'
for (var key in options.data) {
data += key+'='+options.data[key]+'&'
}
// data = 'k1=v1&k2=v2&k3=v3&'
data = data.substring(0,data.length-1)
}
if (typeof options.data === 'string') {
data = options.data
}
// 判断请求方式
if (options.type.toLowerCase() === 'get') {
var time = ''
time = options.cache ? '' : Date.now()
// 2.打开连接
xhr.open(options.type,options.url+'?'+data+'&_='+time,true) // 默认true,异步
// 3.发送请求
xhr.send(null) // get请求传null
}
if (options.type.toLowerCase() === 'post') {
// 2.打开连接
xhr.open(options.type,options.url,true) // 默认true,异步
// post 请不会有缓存问题
// 设置请求头,作用 模拟表单 post 请求提交数据,在send方法之前设置
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded")
// 3.发送请求
xhr.send(data) // post请求 要传递的参数在此传 }
// 4.等待请求/响应状态 // xhr.readyState 请求状态,0-4状态改变会触发一个readystatechange事件
xhr.onreadystatechange = function (){
// console.log( xhr.readyState );// 2 3 4
if (xhr.readyState === 4) {// 请求完成
// xhr.status 响应状态
if (xhr.status === 200) {
// OK 响应就绪
// xhr.responseText 响应的数据
// options.success(xhr.responseText)
// 支持dataType配置
if (options.dataType === 'json') {
var json = JSON.parse(xhr.responseText)
options.success(json)
} else if (options.dataType === 'xml') {
options.success(xhr.responseXML)
} else {
options.success(xhr.responseText)
}
} else {
// console.log(xhr.status)
options.error(xhr.status)
}
}
}
}
封装 AJAX
function ajax(options) {
// 先准备一个默认值
var defInfo = {
url: '', // 地址不需要默认值
type: 'GET', // 请求方式的默认值是 GET
async: false, // 默认值是异步
data: '', // 参数没有默认值
dataType: 'string', // 默认不需要执行 json.parse
success () {}, // 默认是一个函数
}
// 先来判断一下有没有传递 url,如果没有,直接抛出异常
if (!options.url) {
throw new Error('url 必须传递')
}
// 有了 url 以后就,我们就把用户传递的参数和我们的默认数据合并
for (let key in options) {
defInfo[key] = options[key]
}
// 接下来的一切我们都是使用我们的 defInfo 就可以了
// 第一步就是判断参数 data
// data 可以不传递,可以为空
// data 也可以是一个 key=value&key=value 格式的字符串
// data 也可以是一个对象
// 否则就抛出异常
if (!(typeof defInfo.data === 'string' && /^(\w+=\w+&?)*$/.test(defInfo.data) || Object.prototype.toString.call(defInfo.data) === '[object Object]')) {
throw new Error('请按照要求传递参数')
}
// 参数处理完毕以后,在判断 async 的数据类型
// 只能传递 布尔数据类型
if (typeof defInfo.async !== 'boolean') {
throw new Error('async 参数只接受布尔数据类型')
}
// 在接下来就判断 type
// 请求方式我们只接受 GET 或着 POST
if (!(defInfo.type.toUpperCase() === 'GET' || defInfo.type.toUpperCase() === 'POST')) {
throw new Error('目前本插件只接受 GET 和 POST 方式,请期待更新')
}
// 接下来就是判断 success 的判断,必须是一个函数
if (Object.prototype.toString.call(defInfo.success) !== '[object Function]') {
throw new Error('success 只接受函数数据类型')
}
// 参数都没有问题了
// 我们就要把 data 处理一下了
// 因为 data 有可能是对象,当 data 是一个对象的时候,我们要把它转换成一个字符串
var str = ''
if (Object.prototype.toString.call(defInfo.data) === '[object Object]') {
for (let attr in defInfo.data) {
str += `${attr}=${defInfo.data[attr]}&`
}
str = str.slice(0, -1)
defInfo.data = str
}
// 参数全部验证过了以后,我们就可以开始进行正常的 ajax 请求了
// 1. 准备一个 ajax 对象
// 因为要处理兼容问题,所以我们准备一个函数
function createXHR() {
if (XMLHttpRequest) {
return new XMLHttpRequest()
} else {
return new ActiveXObject('Microsoft.XMLHTTP')
}
}
// 2. 创建一个 ajax 对象
var xhr = createXHR()
// 3. 进行 open
xhr.open(defInfo.type, defInfo.url + (defInfo.type.toUpperCase() === 'GET' ? `?${defInfo.data}&_=${new Date().getTime()}` : ''), defInfo.async)
if (defInfo.type.toUpperCase() === 'POST') {
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
}
// 4. 进行 send
xhr.send((defInfo.type.toUpperCase() === 'POST' ? `${defInfo.data}` : ''))
// 5. 接受响应
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && /2\d{2}/.test(xhr.status)) {
// 表示成功,我们就要执行 success
// 但是要进行 dataType 的判断
if (defInfo.dataType === 'json') {
defInfo.success(JSON.parse(xhr.responseText))
} else {
defInfo.success()
}
}
}
}