1.原生AjaxGET获取
//步骤一:创建异步对象
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.原生ajaxpost获取
//创建异步对象
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获取
fetch('路径').then(i=>{
i.json().then(data=>{
console.log(data)
}).catch(error=>{
console.log('煮熟的鸟飞了')
})
}).catch(error=>{
console.log('刚开始就错了')
})
4.Jquery获取数据Jquery获取
$.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获取
**this.$axios.get('路径').then(res=>{
//获取请求回来的数据
})**
6.PromisePromise获取
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)
})