用Promise封装一个AJAX函数
AJAX即“Asynchronous JavaScript and XML”(异步的JavaScript与XML技术),
AJAX的优点是不重载当前页面的情况下,可以向服务器请求新内容。
发起AJAX的过程:
1,创建XMLHttpRequest对象
1
| const xhr = new XMLHttpRequest();
|
2,监听xhr的readyState变化
1 2 3 4 5 6 7 8 9 10 11
| xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { console.log(xhr.responseText); } else { console.log(xhr.status); } } };
|
3,open 规划请求参数
1 2 3 4
|
xhr.open(method, url, true);
|
4,send 发送请求
利用promise封装
接下来,用Promise简单的封装一个AJAX函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| function ajax(method, url, params) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { resolve(xhr.responseText); } else { reject(xhr.status); } } };
if (method === 'get' || method === 'GET') { if (typeof params === 'object') { 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(); }
if (method === 'post' || method === 'POST') { xhr.open(method, url, true); xhr.setRequestHeader("Content-type", "application/json; charset=utf-8"); xhr.send(JSON.stringify(params)); } }); }
ajax('GET' , '127.0.0.1/data.json', { data:{ name:'www', age:14, } }).then(res=>{ console.log(res); })
|