JavaScript原生封裝ajax請求和Jquery中的ajax請求
-
前言:ajax的神奇之處在於JavaScript 可在不過載頁面的情況與 Web 伺服器交換資料,即在不需要重新整理頁面的情況下,就可以產生區域性重新整理的效果。Ajax 在瀏覽器與 Web 伺服器之間使用非同步資料傳輸(HTTP 請求),當然也可同步,這樣就可使網頁從伺服器請求少量的資訊,而不是整個頁面。Ajax使我們的專案更小、更快,更友好,在前端開發有很高的地位,也是面試題的熱點。本次測試是在localhost本地環境。
1、原生ajax
(1)html前端程式碼get請求方式
- 建立一個ajax例項xhr
- open()方法傳入三個引數,第一個是請求方式(一般為get和post),第二個引數是請求地址,第三個布林值,true代表非同步,false代表同步
- send傳送資料(get用不上,get傳送的資料一般在連結後面,所以為顯式傳值,形式為鍵值對)
- 繫結監聽函式判斷狀態碼
- xhr.responseText得到返回資料
var xhr = new XMLHttpRequest() xhr.open("GET","js/text.js",true) xhr.send() xhr.onreadystatechange = function(){// if(xhr.readyState === 4&& xhr.status === 200){ var data = xhr.responseText var datas = JSON.parse(data) console.log(datas) } }
-
控制檯輸出
(2)html前端程式碼post請求方式
- post傳遞方式需要設定頭資訊,實測簡單的請求不設定也是可以
- 這裡的傳值是放在send()方法裡面的,所以為隱式傳值,其他的都和get相同
var xhr = new XMLHttpRequest() xhr.open("POST","js/text.js",true) xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.send() xhr.onreadystatechange = function(){ if(xhr.readyState === 4&& xhr.status === 200){ var data = xhr.responseText var datas = JSON.parse(data) console.log(datas) } }
-
控制檯輸出
(3)被請求js程式碼
{ "name":"小明", "age":24, "array":[1,51,3,4,4,6,64] }
2、函式封裝
- 這裡函式封裝的一個ajax方法,用的時候直接呼叫該方法,傳入設定引數即可
-
引數有請求型別type,請求地址url,傳入資料data(本案例無,沒有也需要“”佔位),請求成功返回函式success(也可多加一個失敗返回函式)
(1)前端JS程式碼
function Ajax(type, url, data, success){ var xhr = null;// 初始化xhr if(window.XMLHttpRequest){//相容IE xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject('Microsoft.XMLHTTP') } var type = type.toUpperCase(); var random = Math.random(); //建立隨機數 if(type == 'GET'){ if(data){ xhr.open('GET', url + '?' + data, true);//如果有資料就拼接 } else { xhr.open('GET', url + '?t=' + random, true);//如果沒有資料就傳入一個隨機數 } xhr.send(); } else if(type == 'POST'){ xhr.open('POST', url, true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send(data); } xhr.onreadystatechange = function(){// 建立監聽函式 if(xhr.readyState == 4&&xhr.status == 200){ success(xhr.responseText); } } } Ajax('get', 'js/text.js', "", function(data){//呼叫函式 console.log(JSON.parse(data)); });
(2)被請求js程式碼
{ "name":"小明", "age":24, "array":[1,51,3,4,4,6,64] }
-
控制檯輸出
3、Jquery中的Ajax(先引入Jquery)
(1)前端簡單的JS程式碼
- jquery中的ajax是被庫封裝好了的,我們直接用即可,下面是簡單的ajax請求,它也有很多引數,但基礎的就這些了
$.ajax({ url:"./js/text.js", type:"GET", dataType:"json", success:function(data){ console.log(data) }, error:function(res){ console.log("請求失敗!") } })
(2)被請求js程式碼
{ "name":"小明", "age":24, "array":[1,51,3,4,4,6,64] }
- 控制檯輸出
- 以上如有不對之處,請大家多多指正,謝謝!