參考自 阮一峰JS教程
AJAX成為了javascript腳本發(fā)送HTTP請求的代名詞,可同步可異步,一般指異步,同步會阻塞
基本四步驟:
1.創(chuàng)建AJAX對象
2.監(jiān)聽事件
3.open
4.send
經(jīng)常用法
var xhr = new XMLHttpRequest();
// 指定通信過程中狀態(tài)改變時的回調(diào)函數(shù)
xhr.onreadystatechange = function(){
// 通信成功時,狀態(tài)值為4
if (xhr.readyState === 4){
if (xhr.status === 200 || xhr.status === 304){
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
// open方式用于指定HTTP動詞、請求的網(wǎng)址、是否異步
xhr.open('GET', '/endpoint', true);
// 發(fā)送HTTP請求
xhr.send(null);
XMLHttpRequest對象
//從創(chuàng)建這個對象開始,后面的很多東西都是它的實例,
不要問這個對象從哪來,把它看成和date,Arry之類的就好了
var xhr=new XMLHttpRequest()
XMLHttpRequest對象的屬性
readyState
表示XMLHttpRequest請求當前所處的狀態(tài)(也可以看作請求的進度條),在請求的時候,它的狀態(tài)會自己變化
0:UNSENT XMLHttpRequest對象已經(jīng)生成,但是open()方法還沒有被調(diào)用
1:opened open()方法已被調(diào)用,但是send()方法還沒被調(diào)用
2:HEADERS_RECEIVED,表示后端的send方法已經(jīng)調(diào)用,頭信息和狀態(tài)碼已經(jīng)收到
3:LOADING,表示正在接收服務器傳來的數(shù)據(jù)
4:DONE表示服務器已經(jīng)完全接收或者接收失敗
onreadystatechange
//這個請求指向一個函數(shù)
xhr.onreadystatechange=function(){}
//請求時,readyState會變化,
每變化一次,這個函數(shù)就會被調(diào)用一次
response基友群
responseType用來指定返回數(shù)據(jù)的類型,可以是字符串,JSON,ArrayBuffer對象.Dom對象等
responseXML屬性返回從服務器接收到的Document對象
responseText從服務器接收到的字符串,我們用到最多的還是它了
status好姐妹
status
HTTP請求得到的狀態(tài)碼,最多用到的是200,訪問正常
304: not Modified未修改(從緩存過去)
404 : not found未發(fā)現(xiàn)網(wǎng)址
500 : 服務器發(fā)生錯誤
//基本上只有2xx和3xx的狀態(tài)碼表示正常
statusText
同樣表示HTTP狀態(tài),返回一個字符串
和status不同的是,他還包含狀態(tài)信息,比如'200 OK'
XMLHttprequest方法
open()
配置HTTP請求參數(shù)
常用參數(shù)有open(method,url,true/false,username,password)
請求的方法,地址,是否異步,默認為true(異步),用于驗證的用戶名和密碼
send()
注意:所有監(jiān)聽事件,必須在send()方法調(diào)用前設(shè)定
實際發(fā)出http請求
send方法可以發(fā)送多種數(shù)據(jù),包括表單,文件等
- 如果不帶參數(shù),表明HTTP請求只包含頭部信息,也就是只有一個URL,常用于GET請求
- 如果帶參數(shù),表示除了頭信息,還有具體數(shù)據(jù),常用于POST請求
jQuery ajax寫法
$.ajax({
method:'GET',
url:'',
data:{}
}).done(function(result){console.log(result)}).fail(function(){
})
JQ發(fā)送JSONP
請求這個接口后得到
func({數(shù)據(jù)})
$.ajax({
url:'http://platform.sina.com.cn/slide/album_tech',
dataType:'jsonp',
jsonp:'jsoncallback',
data:{
app_key:'1271687855',
num:'3',
page:'1'
} //會請求 http://platform.sina.com.cn/slide/album_tech?jsoncallback=func&app_key=1271687855&num=3&page=4
}).done(function(ret){
console.log(ret)
})
實例
//使用ajax模擬 加載更多
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<style>
.newslist div {
line-height: 60px;
text-align: center;
margin: 10px 0;
background: #f1f1f1;
}
#loadmore {
display: block;
margin: 30px auto;
text-align: center;
width: 200px;
height: 50px;
outline: none;
background: blue;
border: none;
color: #fff;
}
</style>
</head>
<body>
<div class="newslist">
<div class="news">
新聞1
</div>
<div class="news">
新聞2
</div>
<div class="news">
新聞3
</div>
<div class="news">
新聞4
</div>
</div>
<div><button id='loadmore'>加載更多</button></div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js'></script>
<script>
var index = 5
$('#loadmore').click(function () { //ajaxJQ寫法一
$.ajax({
method: 'GET',
url: '/loadMore',
data: {
index: index,
length: 4
}
}).done(function (result) {
console.log(result);
$.each(result, function (index, value) {
$('.newslist').append('<div>' + value + '</div>')
})
index += 4
})
})
/*var loadMore = document.getElementById('loadmore'); //原生寫法
var newsList = document.getElementsByClassName('newslist')[0];
var xhr = new XMLHttpRequest();
var index = 5;
var isloading=false;
loadMore.addEventListener('click', function () {
if(isloading){return}
isloading=true;
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200 || xhr.status === 304) {
var arr = JSON.parse(xhr.responseText)
console.log(arr)
render(arr)
}else{
console.log('出錯了')
}
isloading=false;
}
}
xhr.open('get', '/loadMore?index=' + index + '&length=4'); //請求的參數(shù)索引和長度
xhr.send()
index += 4
})
function render(arr) {
var fragment = document.createDocumentFragment();
for (var i = 0; i < arr.length; i++) {
var div = document.createElement('div');
div.innerText = arr[i];
fragment.appendChild(div)
}
newsList.appendChild(fragment)
}*/
</script>
</body>
</html>
//后端 router.js
app.get('/loadMore',function(req,res){
var curIdx=req.query.index
var len=req.query.length
var data=[]
for(var i=0;i<len;i++){
data.push('新聞'+(parseInt(curIdx)+i))
}
res.send(data)
})