1.原生ajax
<script type="text/javascript">
window.onload = function() {
var oBtn = document.getElementById('btn');
oBtn.onclick = function() {
var xmlHttp = new XMLHttpRequest();
//2.绑定监听函数
xmlHttp.onreadystatechange = function() {
//异步请求必须监听,同步可以直接写send后面
//判断数据是否正常返回
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
//6.接收数据
alert(xmlHttp.responseText);
}
}
//3.绑定处理请求的地址,true为异步,false为同步
//GET方式提交把参数加在地址后面?key1:value&key2:value
xmlHttp.open("POST", "1.txt", true);
//4.POST提交设置的协议头(GET方式省略)
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//不建议重写正常发送的头部字段
//POST提交将参数,如果是GET提交send不用提交参数
//5.发送请求
xmlHttp.send("name=zjj&age=18");
//xmlHttp.abort()
//xmlHttp=null;
//停止触发事件并且删除引用
}
}
</script>
2.ajax(jquery)
$.ajax({
type: "get",
url: "https://api.apiopen.top/musicRankings",
async: true,
success: function(data) {
for (var j = 0; j < data.result.length; j++) {
for (var i = 0; i < data.result[j].content.length; i++) {
$('#ul1').append('<li>' + data.result[j].name + '---------------' +
'<span>' + '歌曲名:' + data.result[j].content[i].title + '</span> ' +
'<span>' + '歌曲编号:' + data.result[j].content[i].album_id + '</span> ' +
'<span>' + '歌手:' + data.result[j].content[i].author + '</span> ' +
'</li>');
}
console.log(data.result[j].name);
}
},
error: function(err) {
alert("data" + err + '111');
}
});
3.axios
promise语法糖,promise不是参与通信的,可以在axios外再嵌套一层promise来适用于对不同的返回数据进行不同的处理。
axios({
//axios.all(arr).then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
//}));
//arr[0]==axios.get('/user/12345/permissions')
//axios可以用这种方法处理
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});