Ajax与异步编程
Ajax含义:异步无刷新技术。
Ajax的具体实现:例:
<button type="" id="btn">点击</button>
<script src="./jquery-1.11.1.js'"></script>
<script src="./mock-min.js"></script>
<script>
// 原生Ajax
let data=Mock.mock('/getStudent', {
'list|4': [{
'id|+1': 1,
"name": '@cname()',
addr: '@county(true)',
'age|18-30': 1,
birth: '@date()',
'like|1': ['读书', '听音乐', '运动'],
}]
})
btn.onclick = function () {
let xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
xhr.open('GET', '/getStudent', true);
xhr.send(null);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log('数据', JSON.parse(xhr.responseText));
}
}
}
及同步的含义:同一时间只能做一件事情,也就是说一件事情做完才能做另外的事情。
异步实现即多线程。
实现异步有三种方式:
例:1、普通式(但易造成回调地狱)
setTimeout(function () {
setTimeout(function () {
console.log('hello world!');
setTimeout(function () {
console.log('hello world!');
}, 2000)
}, 2000)
console.log('hello world!');
}, 2000)
2、promise实现异步及解决回调地狱
例:
let ress = function (time) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve();
}, time)
})
}
ress(2000).then(function () {
console.log('你好呀!');
return ress(2000);
}).then(function () {
console.log('你好呀!');
return ress(2000);
}).then(function () {
console.log('你好呀!');
return ress(2000);
}).then(function () {
console.log('你好呀!');
return ress(2000);
}).then(function () {
console.log('你好呀!');
})
3、ES 7 实现异步的方法 async await,这个称之为异步的终极解决方案
因为这种方式来实现的异步,让异步代码看上去就像同步代码一样
async 是修饰函数的一个关键字,表示一个函数是一个异步的函数
function timer(){
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve('Hello World!!!')
},2000);
});
}
console.log('Hello');
async function test(){
console.log(await timer());
console.log(await timer());
console.log(await timer());
console.log(await timer());
console.log(await timer());
}
test();
console.log('World');
May you live more like yourself than you are bound to.