一.原生js中使用
1 | //1.创建一个XMLHttpRequest类型的对象 |
2 | var xhr = new XMLHttpRequest() |
3 | //2.确定对象发送方式、协议方法,打开连接 |
4 | //open()方法第三个参数要求传入的是bool值,作用是设置请求是否异步执行,默认true,传false同步执行,同步方式执行要先注册事件再调用send,否则readystatechange无法触发 |
5 | xhr.open('GET', './login.php') |
6 | //3.通过连接发送一次请求 |
7 | xhr.send(null) |
8 | //4.响应,判断状态码,指定xhr状态变化事件处理函数 |
9 | xhr.onreadystatechange = function () { |
10 | //通过xhr的readyState判断此次请求的响应是否接收完成 |
11 | if (this.readyState === 4) { |
12 | //通过xhr的responseText获取到响应的响应体 |
13 | console.log(this) |
14 | } |
15 | } |
二.jquery中使用
1 | $.ajax({ |
2 | url: './login.php',//请求地址 |
3 | type: 'post',//请求方法 |
4 | dataType: 'json',//服务端响应数据类型 |
5 | data: { id: 1 },//需要传递到服务端的数据 |
6 | beforeSend: function () {//请求发起之前触发 |
7 | console.log('before') |
8 | }, |
9 | success: function (data) {//请求成功之后触发 |
10 | console.log(data) |
11 | }, |
12 | error: function (err) {//请求失败触发 |
13 | console.log(err) |
14 | }, |
15 | complete: function () {//请求完成触发 |
16 | console.log('completed') |
17 | } |
18 | }) |
还有$.get
和$.post
方法不用写type,方便快捷。
三.Axios
在vue中可以使用vue-resource,但官方不再维护vue-resource,推荐使用axios
<script src="https://cdn.staticfile.org/vue-resource/1.5.1/vue-resource.min.js"></script>
npm install vue-resource --save
1 | //在一个Vue实例内使用$http |
2 | this.$http.get('/someUrl', [options]).then(successCallback, errorCallback); |
3 | this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback); |
4 | //基于全局Vue对象使用http |
5 | Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback); |
6 | Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback); |
7 | //get例子 |
8 | this.$http.get("/xxx/xxx.php",{ |
9 | params:{ |
10 | userId:"101" |
11 | }, |
12 | headers:{ |
13 | token:"abcd" |
14 | } |
15 | }).then(res=>{ |
16 | this.msg=res.data; |
17 | },error=>{ |
18 | this.msg=error; |
19 | } |
20 | }); |
21 | //post例子 |
22 | this.$http.post("/xxx/xxx.php",{userId:"102"},{ |
23 | headers:{ |
24 | access_token:"abc" |
25 | } |
26 | }).then(function(res){ |
27 | this.msg=res.data; |
28 | }); |
- axios在vue/react等都可以用,axios引入或安装
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
npm install axios --save
1 | //http例子 |
2 | axios({ |
3 | url:"/user", |
4 | method:"get",//"post" |
5 | data:{userId:"101"},//Post |
6 | params:{userId:"101"},//Get |
7 | headers:{token:"http-test"} |
8 | }).then(res=>{this.msg=res.data;}) |
9 | //get例子 |
10 | axios.get('/user', { |
11 | params: { |
12 | ID: 123//也可以直接在URL上添加参数/user?ID=123 |
13 | } |
14 | }) |
15 | .then(function (response) { |
16 | console.log(response); |
17 | }) |
18 | .catch(function (error) { |
19 | console.log(error); |
20 | }); |
21 | //post例子 |
22 | axios.post('/user', { |
23 | firstName: 'Fred', //参数firstName |
24 | lastName: 'Flintstone' //参数lastName |
25 | }) |
26 | .then(function (response) { |
27 | console.log(response); |
28 | }) |
29 | .catch(function (error) { |
30 | console.log(error); |
31 | }); |