发布时间:2023-10-14 12:00
1.背景
1.1 AJAX是浏览器上的功能
1.2 准备一个服务器
node server.js
node server.js 8888
启动yarn global add node-dev
node-dev
代替node
,就会自动重启,方便开发1.3 Node.js和server.js是什么?
response.write()
里面只接收字符串,可以把HTML内容加反引号直接写在里面response.write(fs.readFileSync(public/index.html))
2.挑战1
2.1 加载CSS
引入CSS2.2 4个步骤
const request = new XMLHttpRequest()
request.open();
request.open(method, url);
request.open(\'GET\',\'/style.css\')
const request = new XMLHttpRequest() //创建对象
request.open(\'GET\',\'/style.css\') //调用open
request.onload=()=>{ //监听请求成功与否
console.log(\'成功了\')
}
request.onerror=()=>{
console.log(\'失败了\')
}
request.send() //发送请求
2.3 请求成功后如何生效
request.response
(可以log出来)getCSS.onclick = () => {//监听按钮,点击之后就会进行4步骤
const request = new XMLHttpRequest();
request.open(\"GET\", \"/style.css\");
//监听request调用成功还是失败
request.onload = () => {//请求成功完成时调用的函数。
//创建 style 标签
const style = document.createElement(\'style\')
//填写 style 内容
style.innerHTML = request.response
//插到 头 里面
document.head.appendChild(style)
};
request.onerror = () => {
console.log(\"失败了\");
};
request.send(); //发送请求
};
3.挑战2
3.1 加载JS
3.2 步骤
3.3 代码生效
//创建 script 标签
const script = document.createElement(\'script\')
//填写 script 内容
script.innerHTML = request.response
//插到 身体 里面
document.body.appendChild(script)
4挑战3
4.1 加载HTML
4.2 步骤
4.3 生效
const div = document.createElement(\'div\')
div.innerHTML = request.response
document.body.appendChild(div)
5.如果触发错误怎么办?
5.1 onreadystatechange
XMLHttpRequest.onreadystatechange
readyState
属性发生变化就会触发readyState
:一共有5个值request.onreadystatechange = () =>{}
request.readyState
,由于监听的时候已经open调用了,因此没有0和1requst.status
getJS.onclick = () => {
const request = new XMLHttpRequest();
request.open(\"GET\", \"/2.js\"); // readyState = 1
request.onreadystatechange = () => {
console.log(request.readyState);
if (request.readyState === 4) { //下载完成
if (request.status >= 200 && request.status < 300) {
const script = document.createElement(\"script\");
script.innerHTML = request.response;
document.body.appendChild(script);
} else {
alert(\"加载 JS 失败\");
}
}
};
request.send(); // readyState = 2
};
6.加载XML
6.1 步骤
request.responseXML
(因为AJAX的发明之初就是为了XML,只是后来JSON替代了它)
<message>
<warning>
Hello World
warning>
message>
getXML.onclick = () => {
const request = new XMLHttpRequest();
request.open(\"GET\", \"/4.xml\");
request.onreadystatechange = () => {
if (request.readyState === 4) {
if (request.status >= 200 && request.status < 300) {
const dom = request.responseXML;
const text = dom.getElementsByTagName(\"warning\")[0].textContent;
console.log(text.trim()); //trim没有周围的回车
}
}
};
request.send();
};
7.总结
7.1 HTTP是一个框,什么都能往里装
7.2 解析方法
7.3 AJAX