AJAX 代码
获取CSS: getCSS()
1 2 3 4 5 6 7 8 9 10 11 12 13
| getCSS.onclick = function() { const xhr = new XMLHttpRequest(); xhr.open('GET', '/style.css'); xhr.onreadystatechange = () =>{ if(xhr.readyState === 4 && xhr.status === 200){ const style = document.createElement('style'); style.innerHTML = xhr.responseText; document.head.appendChild(style); } } xhr.send(); }
|
获取JS: getJS()
1 2 3 4 5 6 7 8 9 10 11 12
| getJS.onclick = function() { const xhr = new XMLHttpRequest(); xhr.open('GET', '/2.js'); xhr.onload = function() { eval(xhr.responseText); } xhr.send(); }
|
获取HTML: getHTML()
1 2 3 4 5 6 7 8 9 10 11
| getHTML.onclick = function() { const xhr = new XMLHttpRequest(); xhr.open('GET', `/3.htm`); xhr.onload = function() { const div = document.createElement('div'); div.innerHTML = xhr.responseText; document.body.appendChild(div); } xhr.send(); }
|
获取XML: getXML()
1 2 3 4 5 6 7 8 9 10 11 12 13
| getXML.onclick = function() { const xhr = new XMLHttpRequest(); xhr.open('GET', '/4.xml'); xhr.onreadystatechange = () =>{ if (xhr.readyState === 4 && xhr.status === 200) { const xml = xhr.responseXML; const text = xml.getElementsByTagName('warning')[0].textContent; console.log(text.trim()); } } xhr.send(); }
|
获取JSON: getJSON()
1 2 3 4 5 6 7 8 9 10 11 12
| getJSON.onclick = function() { const xhr = new XMLHttpRequest(); xhr.open('GET', '/5.json'); xhr.onreadystatechange = () =>{ if (xhr.readyState === 4 && xhr.status === 200) { const json = JSON.parse(xhr.responseText); console.log(json); } } xhr.send(); }
|
获取分页数据: getPage()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| let index = 1; getPage.onclick = function() { if (index >= 3) { index = 1; } const xhr = new XMLHttpRequest(); xhr.open('GET', `/page${index += 1}`); xhr.onreadystatechange = () =>{ if (xhr.readyState === 4 && xhr.status === 200) { const array = JSON.parse(xhr.responseText); array.forEach(item => { const li = document.createElement('li'); li.textContent = item.id xxx.appendChild(li); }) } } xhr.send(); }
|
异步与 promise


1 2 3 4 5 6 7 8 9 10 11 12 13
| const array = ['1','2','3'].map(parseInt) === const array = ['1','2','3'].map((item, i, arr) => { return parseInt(item, i, arr) })
const array = ['1','2','3'].map(item=>parseInt(item)) console.log(array)
|

改成 Promise



背下来这玩意

小节: Promise

版权声明: 资料来源:饥人谷。任何组织或个人未经许可,禁止转载