初识AJAX

启动步骤

pip install -r requirements.txt
python fast.py or uvicorn fast:app

AJAX 代码

获取CSS: getCSS()

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()

getJS.onclick = function() {
const xhr = new XMLHttpRequest();
xhr.open('GET', '/2.js');
xhr.onload = function() {
// const script = document.createElement('script');
// script.innerHTML = xhr.responseText;
// document.head.appendChild(script);
eval(xhr.responseText);
}
xhr.send();
}

获取HTML: getHTML()

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()

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()

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()

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();
}