# 1. 原生 Ajax GET获取

1
2
3
4
5
6
7
8
9
10
11
12
13
//步骤一:创建异步对象
var ajax = new XMLHttpRequest();
//步骤二:设置请求的url参数,参数一是请求的类型,参数二是请求的url,可以带参数,动态的传递参数starName到服务端
ajax.open('get','路径');
//步骤三:发送请求
ajax.send();
//步骤四:注册事件 onreadystatechange 状态改变就会调用
ajax.onreadystatechange = function () {
if (ajax.readyState==4 &&ajax.status==200) {
//步骤五 如果能够进到这个判断 说明 数据 完美的回来了,并且请求的页面是存在的
    console.log(JSON.parse(ajax.responseText));//输入相应的内容
  }
}

# 2. 原生 ajax post获取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//创建异步对象  
var xhr = new XMLHttpRequest();
//设置请求的类型及url
//post请求一定要添加请求头才行不然会报错
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.open('post', '路径' );
//发送请求
xhr.send();
xhr.onreadystatechange = function () {
// 这步为判断服务器是否正确响应
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};

# 3.fetch 获取数据 fetch获取

1
2
3
4
5
6
7
8
9
fetch('路径').then(i=>{
i.json().then(data=>{
console.log(data)
}).catch(error=>{
console.log('煮熟的鸟飞了')
})
}).catch(error=>{
console.log('刚开始就错了')
})

# 4.Jquery 获取数据 Jquery获取

1
2
3
4
5
6
7
8
9
10
11
12
$.ajax({
type: "POST",//请求方式
url: "路径",//地址,就是json文件的请求路径
dataType: "json",//数据类型可以为 text xml json script jsonp
async:false,//默认异步
   success: function(result){//返回的参数就是 action里面所有的有get和set方法的参数
console.log(result)
},
error:function(err){
console.log('请求开始就失败了')
}
});

# 5.axios 获取数据 axios获取

1
2
3
this.$axios.get('路径').then(res=>{
//获取请求回来的数据
})

# 6.Promise Promise获取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function axios(url){
return new Promise((resolve,reject)=>{
$.ajax({
url:url,
type:'get',
success:(data)=>{resolve({data})},
error:(error)=>{
reject({
status:400,
msg:'数据请求失败!!!'
})
}
})
})
};
axios('./list.json').then(i=>{
console.log(i)
})

# 7. 分装 分装

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
function ajax_method(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");

// 判断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);
}
}

}
更新于

请我喝[茶]~( ̄▽ ̄)~*

高祥 微信支付

微信支付

高祥 支付宝

支付宝

高祥 贝宝

贝宝