04.17 Ajax清晰請求步驟與代碼

Ajax清晰請求步驟與代碼

異步請求ajax的使用在前後臺傳遞數據,優化用戶體驗起著至關重要的角色,那麼下面給大家簡單羅列了一下ajax請求的步驟與代碼。

一、原生JS中的Ajax:

1、使用ajax發送數據的步驟

第一步:創建異步對象

var xhr = new XMLHttpRequest();

第二步:設置 請求行 open(請求方式,請求url):

// get請求如果有參數就需要在url後面拼接參數,
// post如果有參數,就在請求體中傳遞 xhr.open("get","validate.php?username="+name)
xhr.open("post","validate.php");

第三步:設置請求(GET方式忽略此步驟)頭:setRequestHeader()

// 1.get不需要設置
// 2.post需要設置請求頭:Content-Type:application/x-www-form-urlencoded

xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

第四步:設置請求體 send()

// 1.get的參數在url拼接了,所以不需要在這個函數中設置
// 2.post的參數在這個函數中設置(如果有參數)
xhr.send(null) xhr.send("username="+name);

第五步:讓異步對象接收服務器的響應數據

// 一個成功的響應有兩個條件:1.服務器成功響應了 2.異步對象的響應狀態為4(數據解析完畢可以使用了)

xhr.onreadystatechange = function(){ 
if(xhr.status == 200 && xhr.readyState == 4){
console.log(xhr.responseText);
}

ajax-get方式請求案例:

var xhr = new XMLHttpRequest();
xhr.open("get","validate.php?username="+name);
xhr.send(null);
xhr.onreadystatechange = function(){
if(xhr.status == 200 && xhr.readyState == 4){ console.log(xhr.responseText); document.querySelector(".showmsg").innerHTML = xhr.responseText;;
}
}

ajax-post方式請求案例:

var xhr = new XMLHttpRequest(); 

xhr.open("post","validate.php");
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send("username="+name);
xhr.onreadystatechange = function(){
// 判斷服務器是否響應,判斷異步對象的響應狀態
if(xhr.status == 200 && xhr.readyState == 4){
document.querySelector(".showmsg").innerHTML = xhr.responseText;
}
}

二、Jquery中的Ajax

$.ajax({
type:"get",// get或者post
url:"abc.php",// 請求的url地址
data:{},//請求的參數
dataType:"json",//json寫了jq會幫我們轉換成數組或者對象 他已經用JSON.parse弄好了
timeout:3000,//3秒後提示錯誤
beforeSend:function(){
// 發送之前就會進入這個函數
// return false 這個ajax就停止了不會發 如果沒有return false 就會繼續
},
success:function(data){ // 成功拿到結果放到這個函數 data就是拿到的結果
},
error:function(){//失敗的函數
},
complete:function(){//不管成功還是失敗 都會進這個函數
}
})
// 常用
$.ajax({
type:"get",
url:"",
data:{},
dataType:"json",
success:function(data){

}
})

$.ajax() 都可以發

$.post(url,data,success,datatype):本質上只能發送post請求

$.get(url,data,success,datatype):本質上只能發送get請求


分享到:


相關文章: