一、概念
ajax:
????????核心XMLHttpRequest ,在不重新加载整个页面的情况下更新部分数据
promise:
????????承诺,只有三种模式(?pending:执行状态、fulfilled:已成功、rejected:已失败),且不受外界影响,解决回调地域
????????官网地址:https://www.promisejs.org/
axios:
????????基于promise的网络请求库
????????参考地址:使用说明 · Axios 中文说明 · 看云
二、使用(封装)
1、ajax(原生封装)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>1121212</div>
<script>
//封装ajax请求
function fun (options) {
//初始化默认值
options = options || {}
options.type = (options.type || 'POST').toUpperCase()
const params = options.data
// 创建XMLHttpRequest对象
const xhr = new XMLHttpRequest()
//发送请求
if (options.type === "GET") {
xhr.open('GET', options.url + "?" + getParams(params), true)
xhr.send()
} else if (options.type === "POST") {
xhr.open('POST', options.url, true)
//设置请求头
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.send(getParams(params))
}
//设置返回信息格式
xhr.responseType="json"
//接收返回信息
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
options.success(xhr.response)
} else {
options.fail("参数错误" + status)
}
}
}
}
//调用
fun(
{
type: "post",
url: 'http://192.168.166.146:8184/indexPage/readIndexPages',
// url: ' http://192.168.166.146:8184/Topo/getCloudStatus',
data: {
name: 30
},
success: function (text, xml) { // 成功回调
console.log(text, xml);
},
fail: function (status) { // 失败回调
console.log(status);
}
}
)
//处理传值形式
function getParams (data) {
let arr = []
for (const key in data) {
arr.push(`${key}=${data[key]}`)
}
return arr.join('$')
}
</script>
</body>
</html>
2、promise封装ajax
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>1121212</div>
<script>
//封装ajax请求
function fun (options) {
return new Promise((resolve, reject) => {
//初始化默认值
options = options || {}
options.type = (options.type || 'POST').toUpperCase()
const params = options.data
// 创建XMLHttpRequest对象
const xhr = new XMLHttpRequest()
//发送请求
if (options.type === "GET") {
xhr.open('GET', options.url + "?" + getParams(params), true)
xhr.send()
} else if (options.type === "POST") {
xhr.open('POST', options.url, true)
//设置请求头
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.send(getParams(params))
}
//设置返回信息格式
xhr.responseType = "json"
//接收返回信息
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response)
} else {
reject(new Error(xhr.statusText))
}
}
}
xhr.onerror = function () {
reject(new Error(xhr.statusText))
}
//设置接口请求超时时间
setTimeout(() => {
//取消当前请求
xhr.abort()
}, 5000)
})
}
//调用
fun(
{
type: "post",
url: 'http://192.168.166.146:8184/indexPage/readIndexPages',
// url: ' http://192.168.166.146:8184/Topo/getCloudStatus',
data: {
name: 30
},
}
).then((res) => {
console.log(res);
}).catch((reson) => {
console.log(reson);
})
//处理传值形式
function getParams (data) {
let arr = []
for (const key in data) {
arr.push(`${key}=${data[key]}`)
}
return arr.join('$')
}
</script>
</body>
</html>
3、axios(封装)
①、项目中src文件下创建utils文件,文件中创建request.js文件
import axios from 'axios'
export default request = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
②、项目中src文件下创建api文件,里面创建对应模块test.js文件
import request from '@/utils/request'
export function getAllData(params){
return request({
method:'GET',
url:'/xxx',
params,
})
}
③、api文件中创建index.js文件,并且引入api文件下其他js文件
import test1 from './test1'
import test2 from './test2'
import test3 from './test3'
export default {
test1,
test2,
test3,
}
④、挂载全局,在main.js文件中引入api文件下的index.js文件
import api from './api'
Vue.prototype.$api=api
⑤、引用
this.$api.test.getAllData()//传参数调用接口
|