test.html
1.92 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
<script>
ajax('http://localhost:7001/',null,'post')
function ajax(url,data,method,success) {
// 异步对象
var ajax = new XMLHttpRequest();
// get 跟post 需要分别写不同的代码
if (method=='get') {
// get请求
if (data) {
// 如果有值
url+='?';
url+=data;
}else{
}
// 设置 方法 以及 url
ajax.open(method,url);
// send即可
ajax.send();
}else{
// post请求
// post请求 url 是不需要改变
ajax.open(method,url);
// 需要设置请求报文
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.setRequestHeader('Authorization','Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImxpbWluIiwiaWF0IjoxNTczODAwMTMyfQ.-AFpvyVbZOL6OEwRbxY8AezoDS-YR--TsaaAb3ze358')
// 判断data send发送数据
if (data) {
// 如果有值 从send发送
ajax.send(data);
}else{
// 木有值 直接发送即可
ajax.send();
}
}
// 注册事件
ajax.onreadystatechange = function () {
// 在事件中 获取数据 并修改界面显示
if (ajax.readyState==4&&ajax.status==200) {
// console.log(ajax.responseText);
// 将 数据 让 外面可以使用
// return ajax.responseText;
// 当 onreadystatechange 调用时 说明 数据回来了
// ajax.responseText;
// 如果说 外面可以传入一个 function 作为参数 success
success(ajax.responseText);
}
}
}
</script>
</html>