原生ajax,现在基本已经没人使用都是用封装好的ajax
var xmlhttp = new XMLHttpRequest();
const formData = new FormData();
formData.append("cardFile", file);
//POST 请求的请求参数,不能拼接在地址栏后面
//发送给后台的参数不能在链接后面拼,链接属于GET请求,因此必须放在发送里面拼
xmlhttp.open("POST", "http://你的请求地址", true);
//POST得设置一下请求头信息setRequestHeader 固定写法 请求头的名 请求头的值
//发送请求post请求的参数传递给 键值对拼写,用&隔开
xmlhttp.send(formData);
xmlhttp.onreadystatechange = function() {
//当 readyState 等于 4 且状态为 200 时,表示响应已就绪:200是响应状态码 4: 请求已完成,且响应已就绪
if (xmlhttp.readyState == 4 & xmlhttp.status == 200) {
//接收后台响应的字符串
var jsonStr = xmlhttp.responseText;
var jsonObj = JSON.parse(jsonStr);
console.log(jsonObj.data.info)
that.$emit('successImage', jsonObj.data.info)
}
}
JQuery的AJAX,现在也很常用
$.ajax({
type:"get",
url:'http://你的URL?参数=' + ‘参数’,
headers:{
Content-Type: application/json;charset=UTF-8,
'key':'value' //你其他的请求头
},
async:true,//同步还是异步
cache:false, // 不设置ajax缓存
dataType:JSON,//json接收
success: function(res){
if(res.code == '200'){
}
}
});
var postArr = [{
key:value
},{
key:value
}]
$.ajax({
type:"post",
url:'http://你的URL',
data:JSON.stringify(postArr),/转字符串
async:true,//同步还是异步
cache:false, // 不设置ajax缓存
dataType:JSON,
contentType: 'application/json',
success: function(res){
if(res.code == '200'){
}
}
});
axios
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
或者
methods: {
getCityInfo () {
axios.get('http://你的url地址')
.then(this.handGet)
},
handGet(res) {
res = res.data
if (res.ret && res.data) {
const data = res.data
}
},
},
mounted () {//vue生命周期,在模板渲染成html后调用
this.getCityInfo()
}
fetch是基于Promise设计出来的用来取代传统的XMLHttpRequest的,不是对ajax的进一步封装
fetch(url).then(function(response) {
return response.json();
})
.then(function(data) {
console.log(data);
})
.catch(function(e) {
console.log("Oops, error");
});
或者使用箭头函数就会更加简洁了
fetch(url).then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))
可以很明显看到callback的使用,我们还可以使用 async、await,就可以像写同步代码一样来写异步代码
// async function
async function fetchAsync () {
let response = await fetch('https://api.github.com');
let data = await response.json();
return data;
}
fetchAsync()
.then(data => console.log(data))
注意: 对于async和await的使用还是很明确的,就是一般我们在一个异步函数之前添加 await 关键词,然后在这个 await 的相关代码外面使用的时 async 函数,这样的结合才是合适的。