发起ajax请求方法

120 阅读2分钟

原生Ajax

发起GET请求

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

//2.调用open函数(二选一)
xhr.open('GET','http://www.liulongbin.top:3006/api/getbooks') //不带参
xhr.open('GET','http://www.liulongbin.top:3006/api/getbooks?id=1') //带参(在url地址后拼接参数,叫做查询字符串)
  
//3.调用send函数
xhr.send();

//4.监听onreadystatechange事件
xhr.onreadystatechange = function(){
    if(xhr.readyState === 4 && xhr.status === 200)
        console.log(xhr.responseText); //获取服务器响应的数据
}

发起POST请求

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

//2.调用open函数
xhr.open('POST','http://www.liulongbin.top:3006/api/addbook')

//3.调用Content-Type属性(固定写法)
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

//4.调用send函数,同时将数据以查询字符串的形式提交给服务器
xhr.send('bookname=水浒传&author=施耐庵&publisher=天津图书出版社');

//5.监听onreadystatechange事件
xhr.onreadystatechange = function(){
    if(xhr.readyState === 4 && xhr.status === 200)
        console.log(xhr.responseText); //获取服务器响应的数据
}

jQuery

基于xhr对象

发起GET请求

$.get('http://www.baidu.com',function(res){   })        //不带参
$.get('http://www.baidu.com',{id:1},function(res){   }) //带参数

发起POST请求

$.post('http://www.baidu.com',function(res){   })                    //不带参
$.post('http://www.baidu.com',{id:1,gender:'女'},function(res){   }) //带参数

发起GET或POST请求

$.ajax({
    type: 'GET', //请求的方式,GET或POST
    url: 'http://www.baidu.com',  //请求的URL地址
    data: { id:1 }, //请求要携带的数据(若不带参可以省略)
    success: function(res){} //请求成功后的回调函数
})

Axios

发起GET请求

//1.请求的URL地址
var url = 'http://www.liulongbin.top:3006/api/get';

//2.请求的参数对象
var paramsObj = { name: 'zs', age: 20 };

//3.调用axios.get()发起GET请求,then里面是成功后的回调函数
axios.get(url,{ params: paramsObj }).then(function(res){
    console.log(res.data);
})

发起POST请求

//1.请求的URL地址
var url = 'http://www.liulongbin.top:3006/api/post';

//2.请求的参数对象
var dataObj = { location: '北京', address: '顺义' };

//3.调用axios.post()发起POST请求,then里面是成功后的回调函数
axios.post(url, dataObj).then(function(res){
    console.log(res.data);
})

直接发起Axios请求

axios({
    method: 'GET',
    url: 'http://www.liulongbin.top:3006/api/get',
    params: {  //get的参数要通过params提供
        name: 'zs',
        age: 20
    },
}).then(function(res){
    console.log(res.data);
})
axios({
    method: 'POST',
    url: 'http://www.liulongbin.top:3006/api/post',
    data: {  //post的参数要通过data提供
        name: '哇哈哈',
        age: 18,
        gender: '女'
    },
}).then(function(res){
    console.log(res.data);
})