Ajax詳細獲取資料
1.原生AjaxGET獲取
var ajax = new XMLHttpRequest();
ajax.open('get','路徑');
ajax.send();
ajax.onreadystatechange = function () {
if (ajax.readyState==4 &&ajax.status==200) {
console.log(JSON.parse(ajax.responseText));
}
}
2.原生ajaxpost獲取
var xhr = new XMLHttpRequest();
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: "路徑",
dataType: "json",
async:false,
success: function(result){
console.log(result)
},
error:function(err){
console.log('請求開始就失敗了')
}
});
5.axios獲取資料axios獲取
this.$axios.get('路徑').then(res=>{
})
6.分裝分裝
function ajax_method(url,data,method,success) {
var ajax = new XMLHttpRequest();
if (method=='get') {
if (data) {
url+='?';
url+=data;
}else{
}
ajax.open(method,url);
ajax.send();
}else{
ajax.open(method,url);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
if (data) {
ajax.send(data);
}else{
ajax.send();
}
}
ajax.onreadystatechange = function () {
if (ajax.readyState==4&&ajax.status==200) {
success(ajax.responseText);
}
}
}