共计 1522 个字符,预计需要花费 4 分钟才能阅读完成。
/** | |
* 简单的异步操作 | |
*/ | |
function callback() {console.log(` 我是一个回调函数 `); | |
} | |
console.log(` 异步之前 `); | |
setTimeout(callback, 1000); | |
console.log(` 异步之后 `); | |
/** | |
* ajax 就是典型的异步操作 | |
*/ | |
// 发起 ajax 的过程 | |
const XHR = new XMLHttpRequest(); | |
console.log(XHR); | |
XHR.onreadystatechange = function() {if (XHR.readyState === 4) {if (XHR.status === 200) {console.log(XHR.responseText); | |
} else {console.log(XHR.status); | |
} | |
} | |
}; | |
XHR.open('GET', `https://jsonplaceholder.typicode.com/users`, true); | |
XHR.send(); | |
/** | |
* jQuery 请求 | |
*/ | |
$.ajax({ | |
type: 'get', | |
url: `https://jsonplaceholder.typicode.com/users`, | |
dataType: 'json', | |
success: function(res) {console.log(res); | |
}, | |
error: function(err) {console.log(err); | |
} | |
}); | |
/** | |
* 用 Promise 简单的封装一个 AJAX 函数 | |
*/ | |
function myAjax(method, url, params) {return new Promise((resolve, reject) => {const XHR = new XMLHttpRequest(); | |
XHR.onreadystatechange = function() {if (XHR.readyState === 4) {if (XHR.status === 200) {console.log(XHR.responseText); | |
} else {console.log(XHR.status); | |
} | |
} | |
}; | |
// get | |
if (method === 'get' || method === 'GET') {if (typeof params === 'object') { | |
// params 拆解成字符串 | |
params = Object.keys(params) | |
.map(function(key) { | |
return (encodeURIComponent(key) + | |
'=' + | |
encodeURIComponent(params[key]) | |
); | |
}) | |
.join('&'); | |
} | |
url = params ? url + '?' + params : url; | |
XHR.open(method, url, true); | |
XHR.send();} | |
//post | |
if (method === 'post' || method === 'POST') {XHR.open(method, url, true); | |
XHR.setRequestHeader( | |
'Content-type', | |
'application/json; charset=utf-8' | |
); | |
XHR.send(JSON.stringify(params)); | |
} | |
}); | |
} | |
/** | |
* 使用定时器来模拟异步操作 | |
* | |
*/ | |
let p = new Promise(function(resolve, reject) {console.log(resolve); // 成功之后的回调 | |
console.log(reject); // 失败时候的回调 | |
setTimeout(() => {resolve(100); | |
}, 1000); | |
}); | |
p.then(function(data) {console.log(data); | |
}); |
正文完