Ajax詳細獲取資料
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)
})
7.分裝分裝
function ajax_method(url,data,method,success) {
// 異步物件
var ajax = new XMLHttpRequest();
// get 跟post 需要分別寫不同的代碼
if (method=='get') {
// get請求
if (data) {
// 如果有值
url+='?';
url+=data;
}else{
}
// 設定 方法 以及 url
ajax.open(method,url);
// send即可
ajax.send();
}else{
// post請求
// post請求 url 是不需要改變
ajax.open(method,url);
// 需要設定請求報文
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// 判斷data send發送資料
if (data) {
// 如果有值 從send發送
ajax.send(data);
}else{
// 木有值 直接發送即可
ajax.send();
}
}
// 注冊事件
ajax.onreadystatechange = function () {
// 在事件中 獲取資料 并修改界面顯示
if (ajax.readyState==4&&ajax.status==200) {
// console.log(ajax.responseText);
// 將 資料 讓 外面可以使用
// return ajax.responseText;
// 當 onreadystatechange 呼叫時 說明 資料回來了
// ajax.responseText;
// 如果說 外面可以傳入一個 function 作為引數 success
success(ajax.responseText);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/162614.html
標籤:其他
下一篇:微信小程式授權登陸
