ajax | 青训营笔记

106 阅读1分钟

ajax | 青训营笔记

这是我参与「第四届青训营 」笔记创作活动的的第5天。

  1. ajax重复请求问题

很简单,添加一个标识变量即可。

btn.onclick = function() {

                //如果正在发送,则取消该请求,创建一个新请求
                if(isSending) xhr.abort();

                //1.创建对象
                xhr = new XMLHttpRequest();

                //修改标识变量
                isSending = true;

                //2.初始化 设置请求方法和url
                xhr.open('GET', 'http://127.0.0.1:8000/server?a=100&b=200&c=300');
                //3.发送
                xhr.send();
                // 4.事件绑定 处理服务端返回的结果
                //readystate 是xhr对象中的属性,表示状态0 1 2 3 4
                xhr.onreadystatechange = function(){
                    //服务端返回了所有结果时
                    if(xhr.readyState === 4) {
                        isSending = false;
                        if(xhr.status >= 200 && xhr.status < 300){
                            //处理结果 行 头 空行 体
                            //1.相应行
                            console.log(xhr.status); //状态码
                            console.log(xhr.statusText); //状态字符串
                            console.log(xhr.getAllResponseHeaders()); //所有响应头
                            console.log(xhr.response); //响应体

                            result.innerHTML = xhr.response; 
                        }
                    }
                }
            }
  1. axios获取请求出现跨域问题

在通过axios获取请求时,即使设置了请求头仍会出现跨域问题。如图:

Snipaste_2022-07-27_09-48-14.png 解决方法:

// 创建应用对象
const app = express();

//不用设置响应头也能解决问题实现跨域
const cors=require('cors');
app.use(cors());
  1. 超时设置
//超时设置2s
                xhr.timeout = 2000;
                //超时回调
                xhr.ontimeout = function () {
                    alert('网络异常,请稍后重试');
                }
                //网络异常回调
                xhr.onerror = function () {
                    alert('你的网络有问题');
                }
  1. favicon设置

改变网页图标,只用添加如下代码: <link rel="shortcut icon" type="image/x-icon" href="../static/favicon.ico" rel="external nofollow"/>
href改成自己图表位置即可。

5. 自定义html代码段

在vscode中点击'管理'-> '配置用户代码段' -> 'html'。 在文件中根据自己需求添加类似如下代码:

{
	"html:5": {
		"prefix": "!",
		"body": [
			"<!DOCTYPE html>",
			"<html>",
			"<head>",
				"\t<meta charset=\"UTF-8\">",
				"\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">",
				"\t<meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">",
				"\t<title>mouguawang</title>",
			"</head>",
			"<body>",
				
			"</body>",
			"</html>",
		],
		"description": "HTML5"
	}

}