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
|
let btn = document.getElementById("btn"); let demo = document.getElementById("#demo");
const ajax_post_promise = (url, parameter = {}) => { return new Promise(function(resolve, reject) { let xhr = new XMLHttpRequest(); xhr.onreadystatechange = () { if (xhr.readyState == 4) { if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { resolve(JSON.parse(xhr.responseText)); } } } xhr.open('post', url, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded') xhr.send(parameter.body); }) };
const ajax_get_promise = (url, parameter = {}) => { return new Promise((resolve, reject) => { let xhr = new XMLHttpRequest(); let param = Object.entries(parameter).map((arrItem, index) => `?${arrItem[0]}=${arrItem[1]}`); xhr.onreadystatechange = () { if (xhr.readyState == 4) { if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { resolve(JSON.parse(xhr.responseText)); } } } xhr.open('get', url + param, true); xhr.send(null); }) };
ajax_post_promise('http://localhost:3020/users/') .then((res) => console.log(res)) .catch((err) => console.log(err));
ajax_get_promise(('http://localhost:3020/users/')) .then((res) => console.log(res)) .catch((err) => console.log(err));
|
近期评论