- 前言: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]
}
