<!DOCTYPE html>
<html lang="zh-cn">
<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>
<script src="./tool.js"></script>
</head>
<body>
<h1>这是第一个网页</h1>
<button id="but1">这是第1个but</button>
<button id="but2">这是第2个but</button>
<button id="but3">这是第3个but</button>
<button id="but4">这是第4个but</button>
<script>
//原生ajax
document.querySelector('#but1').addEventListener("click", () => {
let xhr = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP')
xhr.open('GET', 'http://192.168.0.107:8080/ajax', true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
let obj = JSON.parse(xhr.responseText)
console.log(obj);
}
}
})
//调用自己封装的回调函数
document.querySelector('#but2').addEventListener("click", () => {
myfunction('http://192.168.0.107:8080/ajax', (data) => {
console.log(data);
return myfunction('http://192.168.0.107:8080/ajax1', (data1) => {
console.log(data1);
})
})
})
//调用自己封装的promise函数
document.querySelector('#but3').addEventListener("click", () => {
myaxious('http://192.168.0.107:8080/ajax2')
.then((data) => {
console.log(data);
return myaxious('http://192.168.0.107:8080/ajax1')
.then((data) => {
console.log(data);
return myaxious('http://192.168.0.107:8080/ajax3')
.then((data) => {
console.log(data);
})
})
})
})
//开发常用的async模块
document.querySelector('#but4').addEventListener("click", async() => {
let data = await myaxious('http://192.168.0.107:8080/ajax');
console.log(data);
let data1 = await myaxious('http://192.168.0.107:8080/ajax1');
console.log(data1);
let data2 = await myaxious('http://192.168.0.107:8080/ajax2');
console.log(data2);
let data3 = await myaxious('http://192.168.0.107:8080/ajax3');
console.log(data3);
})
</script>
</body>
</html>
自己所封装的函数
//Promise的访问数据
function myaxious(url) {
let p1 = new Promise((n1,n2)=>{
let xhr=new XMLHttpRequest()||new ActiveXObject("Microsoft.XMLHTTP")
xhr.open("GET",url,true)
xhr.send()
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
//5.数据保存到
// console.log(xhr.responseText)
n1(JSON.parse( xhr.responseText));
}
else if(xhr.readyState==4&&xhr.status==404){
n2(JSON.parse( xhr.responseText));
}
}
})
return p1;
}
//闭包的思想回调
function myfunction(url,cb){
let xhr = new XMLHttpRequest ()||new ActiveXObject("Microsoft.XMLHTTP");
xhr.open("GET",url,true)//默认为true可以不用写,就是要不要异步访问,true为是
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
let obj = JSON.parse(xhr.responseText) ;
cb(obj)
}
}
}
扩展
<script>
//jquery获取ajax数据
$.get('http://192.168.0.107:8080/ajax',(data)=>{
console.log(data);
})
//调用axios工具来访问ajax数据
axios('http://192.168.0.107:8080/ajax1').then(res=>{
console.log(res.data);
}
)
//浏览器自带访问ajax数据
fetch('http://192.168.0.107:8080/ajax2').then(res=>res.json())
.then((data)=>{
console.log(data);
})
</script>