一、XMLHttpRequest
1.1 概念
XMLHttpRequest(XHR)是一種用于在客戶端和服務(wù)器之間發(fā)送HTTP請求的JavaScript API。它允許客戶端在不重新加載整個頁面的情況下向服務(wù)器發(fā)送請求,并根據(jù)服務(wù)器的響應(yīng)更新頁面的局部內(nèi)容。Ajax是基于XHR封裝的。
1.2 使用xhr發(fā)起get請求
步驟
- 創(chuàng)建XHR對象
- 調(diào)用XHR.open()函數(shù)
- 調(diào)用XHR.send()函數(shù)
- 監(jiān)聽xhr.onreadystatechange事件
let xhr = new XMLHttpRequest()
xhr.open('GET','http://www.liulongbin.top:3006/api/getbooks')
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){ //固定寫法 和數(shù)據(jù)對象中的status要區(qū)分
console.log(xhr.responseText)
}
}
?1.3 XHR的readyState屬性
0 |
UNSENT | XHR對象已經(jīng)創(chuàng)建,但是未調(diào)用open方法 |
1 | OPENED | open()方法已經(jīng)被調(diào)用 |
2 | HEADERS_RECEIVED | send()方法已經(jīng)被調(diào)用,響應(yīng)頭也被接受 |
3 | LOADING | 數(shù)據(jù)接收中,此時response屬性已經(jīng)包含部分?jǐn)?shù)據(jù) |
4 | DONE | Ajax請求完成,數(shù)據(jù)傳輸完成或失敗 |
1.4 使用XHR發(fā)起帶參數(shù)的get請求
let xhr = new XMLHttpRequest()
xhr.open('GET','http://www.liulongbin.top:3006/api/getbooks?id=1')
//問號后面拼接的是查詢字符串,多個參數(shù)可以使用&拼接
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
console.log(xhr.responseText)
}
}
1.5 查詢字符串
get請求攜帶參數(shù)的本質(zhì)是將參數(shù)以查詢字符串的形式追加到url的后面
$.get('url',{name:'zs',age:20},function(){})
//等價于
$.get('url?name=zs&age=20',function(){})
1.6 URL編碼
如果url中包含中文,要編碼成英文
encodeURI()//編碼
decodeURI()//解碼
一般來說瀏覽器會自動解析url
1.7?使用xhr發(fā)起post請求
步驟
- 創(chuàng)建xhr對象
- 調(diào)用xhr.open()函數(shù)
- 設(shè)置Content-Type屬性
- 調(diào)用xhr.send()函數(shù),指定要發(fā)送的數(shù)據(jù)
- 監(jiān)聽xhr.onreadystatechange事件
let xhr = new XMLHttpRequest()
xhr.open('POST','http://www.liulongbin.top:3006/api/addbook')
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.send('bookname=八月博客&author=august&publisher=洋槐出版社')
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
console.log(xhr.responseText)
}
}
二、數(shù)據(jù)交換格式
服務(wù)器端與客戶端之間的數(shù)據(jù)傳輸與交換的格式
前端的兩種數(shù)據(jù)格式是XML與JSON
2.1 XML
Extensible Markup Language 可擴(kuò)展標(biāo)記語言,被設(shè)計用來傳輸和存儲數(shù)據(jù)
傳輸效率低,用JS解析比較麻煩
2.2 JSON
JavaScript Object Notation,Javascript對象表示法,本質(zhì)是字符串
輕量級的文本數(shù)據(jù)交換格式,作用上類似于XML
JSON包含對象和數(shù)組兩種結(jié)構(gòu)
對象結(jié)構(gòu)
{
key:value,
key:value,
...
}
其中key必須是雙引號包裹的英文字符串,value的數(shù)據(jù)類型可以是數(shù)字、字符串、布爾值、null、對象、數(shù)組六種類型,不允許出現(xiàn)function和undefined
數(shù)組結(jié)構(gòu)
[ ]括起來的內(nèi)容
數(shù)組結(jié)構(gòu)的類型可以是數(shù)字、字符串、布爾值、null、對象、數(shù)組六種類型
JSON不能寫注釋,不能用單引號表示字符串,最外層必須是對象或數(shù)組格式
作用:在本地與網(wǎng)絡(luò)傳輸數(shù)據(jù)
2.3 JSON與JS中對象的關(guān)系
?JSON實(shí)際上是一種JavaScript對象的表示方式,本質(zhì)是字符串
JSON.parse()
JSON轉(zhuǎn)換為JS對象
JSON.stringfy()
JS對象轉(zhuǎn)換為JSON
// JavaScript對象
const person = {
name: 'Alice',
age: 30,
hobbies: ['reading', 'traveling'],
address: {
street: '123 Main St',
city: 'Anytown',
state: 'CA'
}
};
// 將JavaScript對象轉(zhuǎn)換為JSON格式字符串
const jsonStr = JSON.stringify(person);
console.log(jsonStr);
// 輸出: {"name":"Alice","age":30,"hobbies":["reading","traveling"],"address":{"street":"123 Main St","city":"Anytown","state":"CA"}}
// 將JSON格式字符串轉(zhuǎn)換回JavaScript對象
const jsonObj = JSON.parse(jsonStr);
console.log(jsonObj);
// 輸出: { name: 'Alice', age: 30, hobbies: [ 'reading', 'traveling' ], address: { street: '123 Main St', city: 'Anytown', state: 'CA' } }
三、XMLHttpRequest Level2
3.1 認(rèn)識
新功能
- 設(shè)置HTTP請求的時限
- 使用FormData對象管理表單數(shù)據(jù)
- 可以上傳文件
- 獲取數(shù)據(jù)傳輸?shù)倪M(jìn)度信息
3.2 設(shè)置HTTP請求時限?
let xhr = new XMLHttpRequest()
xhr.timeout = 30
xhr.ontimeout = function(){ //指定超時的回調(diào)函數(shù)
console.log('請求超時')
}
xhr.open('GET','http://www.liulongbin.top:3006/api/getbooks')
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
console.log(xhr.responseText)
}
}
3.3 FormData對象管理表單數(shù)據(jù)?
let fd = new FormData()
//追加數(shù)據(jù)
fd.append('uname','zs')
fd.append('age',18)
let xhr = new XMLHttpRequest()
xhr.open('POST','http://www.liulongbin.top:3006/api/formdata')
xhr.send(fd)
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
console.log(xhr.responseText)
console.log(JSON.parse(xhr.responseText))
}
}
3.4 使用formdata快速獲取表單數(shù)據(jù)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="" class="form1">
<input type="text" name="uname" autocomplete="off">
<input type="password" name="pw">
<button type="submit">提交</button>
</form>
<script>
let form = document.querySelector('.form1')
let xhr = new XMLHttpRequest()
form.addEventListener('submit',function(e){
e.preventDefault()
let fd = new FormData(form)
xhr.open('POST','http://www.liulongbin.top:3006/api/formdata')
xhr.send(fd)
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
console.log(xhr.responseText)
}
}
})
</script>
</body>
</html>
3.5?上傳文件
原生JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="../lib/bootstrap.css">
<style>
img{
width: 300px;
}
.progress{
width: 300px;
margin: 10px;
}
</style>
</head>
<body>
<input type="file" name="" id="file1">
<button id="btnUpload">上傳文件</button>
<div class="progress">
<div class="progress-bar progress-bar-striped active" style="width: 0%">
<span class="sr-only"></span>
</div>
</div>
<div>
<img src="" alt="">
</div>
<script>
const bt1 = document.querySelector('#btnUpload')
let xhr = new XMLHttpRequest()
let fd = new FormData()
bt1.addEventListener('click',function(){
let files = document.querySelector('#file1').files
if(files.length <= 0)return alert('請選擇文件!')
//將用戶上傳的文件添加到formdata中
fd.append('avatar',files[0])
xhr.open('POST','http://www.liulongbin.top:3006/api/upload/avatar')//文件請求類型必須選擇post
xhr.send(fd)
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
let data = JSON.parse(xhr.responseText)
if(data.status === 200){
console.log(data)
document.querySelector('img').src = 'http://www.liulongbin.top:3006' + data.url
}else{
alert(data.message)
}
}
}
})
const span = document.querySelector('.sr-only')
const progress = document.querySelector('.progress-bar')
xhr.upload.onprogress = function(e){
if(e.lengthComputable){ //布爾值 表示當(dāng)前上傳的資源是否具有可計算的長度
let percentComplete = Math.ceil((e.loaded / e.total) * 100)
progress.style.width = `${percentComplete}%`
span.innerHTML = percentComplete + '%'
}
}
</script>
</body>
</html>
jQuery的方法文章來源:http://www.zghlxwxcb.cn/news/detail-425678.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="file" name="" id="file1">
<button id="btnUpload">上傳文件</button>
<div>
<img id="loading" src="./img/loading.gif" alt="" style="display:none;">
</div>
<script src="../lib/jquery.js" ></script>
<script>
$(function(){
//jq實(shí)現(xiàn)loading效果
$(document).ajaxStart(function(){
$('#loading').show()
})
$(document).ajaxStop(function(){
$('#loading').hide()
})
$('#btnUpload').on('click',function(){
let files = $('#file1')[0].files
if(files.length <= 0)return alert('請選擇文件后再上傳')
let fd = new FormData()
fd.append('avatar',files[0])
$.ajax({ //上傳文件必須調(diào)用$.ajax
method:'POST',
url:'http://www.liulongbin.top:3006/api/upload/avatar',
data:fd,
processData:false, //不對formdata中的url進(jìn)行編碼 原樣發(fā)送到服務(wù)器
contentType:false, //使用formdata默認(rèn)的contentType
success:function(res){
console.log(res)
}
})
})
})
</script>
</body>
</html>
四、axios
比jQuery更加輕量,只專注于網(wǎng)絡(luò)數(shù)據(jù)請求文章來源地址http://www.zghlxwxcb.cn/news/detail-425678.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="getbt">GET</button>
<button id="postbt">POST</button>
<button id="axios">直接使用axios</button>
<script src="../lib/jquery.js" ></script>
<script src="../lib/axios.js"></script>
<script>
document.querySelector('#getbt').addEventListener('click',function(){
const url = 'http://www.liulongbin.top:3006/api/get'
const obj = {
name:'zs',
age:18
}
axios.get(url, {params:obj}).then(function(res){
console.log(res)
})
})
document.querySelector('#postbt').addEventListener('click',function(){
const url = 'http://www.liulongbin.top:3006/api/post'
const obj = {
name:'ls',
age:20
}
axios.post(url, obj).then(function(res){
console.log(res)
})
})
document.querySelector('#axios').addEventListener('click',function(){
const url = 'http://www.liulongbin.top:3006/api/get'
const obj = {
name:'ww',
age:22
}
axios({
method:'GET',
url:url,
params:obj,
//data:data, 如果是Post需要將參數(shù)放在data
}).then(function(res){
console.log(res)
})
})
</script>
</body>
</html>
到了這里,關(guān)于前端學(xué)習(xí)--Ajax(3) XHR/axios的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!