一个免费的测试接口
https://api.apiopen.top/getJoke

<body>
<div class="box">
<button id="btn">来段数据</button><br>
<textarea id="text" ></textarea>
</div>
<script>
const btn = document.getElementById("btn");
const txt = document.getElementById("text");
btn.onclick = function(){
getAjax('get','https://api.apiopen.top/getJoke',function(res){
let narr=[];
for(let i=0;i<res.length;i++){
narr.push('\n'+(i+1)+'.'+res[i].text)
console.log(res[i].text);
text.innerHTML=narr;
}
});
}
function getAjax(method,url,callback){
const xhr = new XMLHttpRequest();
xhr.open(method,url);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status>=200 && xhr.status<300){
const res = JSON.parse(xhr.response);
callback(res.result);
}
}
}
}
</script>Promise是ES6引入的异步编程的新解决方案,语法上Promise是一个构造函数,用来封装异步操作并可以获取其成功或者失败的回调结果。
<script>
const btn = document.getElementById("btn");
btn.onclick = function(){
grtAjax('get','https://api.apiopen.top/getJoke',function(res){
console.log(res);
});
}
function grtAjax(method,url,callback){
const p = new Promise((resolve,reject)=>{
const xhr = new XMLHttpRequest();
xhr.open(method,url);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status >= 200 && xhr.status < 300){
resolve(xhr.response);
}else{
reject(xhr.status);
}
}
}
});
p.then(function(value){
const res = JSON.parse(value);
callback(res.result)
},function(reason){
console.error(reason);
})
}
</script>
async
await

<body>
<button>请求数据</button>
<script>
const btn = document.querySelector('button');
function sendAjax(method,url){
return new Promise((resolve,reject)=>{
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open(method,url);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >=200 && xhr.status<300){
resolve(xhr.response);
}else{
reject(xhr.status);
}
}
}
})
}
btn.addEventListener('click',async function(){
let result = await sendAjax('get','https://api.apiopen.top/getJoke');
console.log(result);
})
</script>
</body>Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。
post

get

<template>
<div>
<button @click="post">直接发送POST</button>
<button @click="get">直接发送GET</button>
</div>
</template>
<script>
export default {
data(){
return{}
},
methods:{
async get(){
const {data:res} = await this.$axios.get('https://api.apiopen.top/getJoke',{
params:{id:1}
});
console.log(res);
},
post(){
this.$axios.post('https://api.apiopen.top/getJoke',{name:'yxj',gender:'男'})
.then((res)=>{
console.log(res.data.result);
});
}
}
}
</script>到此这篇关于关于Ajax的封装详解的文章就介绍到这了,更多相关Ajax的封装内容请搜索插件窝以前的文章或继续浏览下面的相关文章希望大家以后多多支持插件窝!