【Ajax】全詳解
1.Ajax的特點
AJAX 的優點
可以無需重新整理頁面而與伺服器端進行通訊
允許你根據使用者事件來更新部分頁面內容
AJAX 的缺點
沒有瀏覽歷史,不能回退
存在跨域問題(同源)
SEO 不友好
2.傳送get / post 請求
頁面:
const btn=document.getElementsByTagName("button")[0] const result=document.getElementById('result')
//傳送get請求 btn.onclick=function (){ //建立物件 const xhr=newXMLHttpRequest() //發給誰 xhr.open('GET','http://localhost:9000/server') xhr.send() xhr.onreadystatechange=function (){ if(xhr.readyState===4){ if(xhr.status>=200&&xhr.status<305){ let msg=xhr.status+' '+xhr.statusText+' ' + xhr.getAllResponseHeaders()+' '+xhr.response result.innerHTML=msg; } } } }
//傳送post請求 result.addEventListener('mouseover',function () { const xhr=new XMLHttpRequest() xhr.open('POST','http://localhost:9000/server') xhr.send('123456') xhr.onreadystatechange=function (){ if(xhr.readyState===4){ if(xhr.status>=200&&xhr.status<305){ result.innerHTML=xhr.response } } } })
伺服器:
const express=require('express') const app=express() app.get('/server', (req,res)=>{ res.setHeader('Access-Control-Allow-Origin','*'); res.send('hello server get'); }); app.post('/server', (req,res)=>{ res.setHeader('Access-Control-Allow-Origin','*'); res.send('hello server post'); }); app.listen(9000,(err)=>{ if(!err){ console.log('啟動成功server') } })
3.請求超時、網路異常和請求取消
//設定響應時間 xhr.timeout=2000; //設定請求超時回撥 xhr.ontimeout = function(){ console.log('超時') } //設定網路異常回調 xhr.onerror = function(){ console.log('網路異常') }
//手動取消,可以藉助這個實現重複傳送請求問題
xhr.abort()
4. jQuery傳送Ajax請求
傳送get請求:
$.get( url , [data] , [callback] , [type])
傳送post請求:
$.post( url , [data] , [callback] , [type])
url:請求的URL 地址
data:請求攜帶的引數
callback:載入成功時回撥函式
type:設定返回內容格式,xml, html, script, json, text, _default
通用方法傳送:
$.ajax({
url:.......
data:.......
type:.......
dataType:.......
success:.......
timeout:.......
error:.......
headers:{
a:.......
b:.......
})
5.axios傳送Ajax請求(多數用這個)
可以將url設定在這裡
axios.defaults.baseURL='url'
傳送 get / post請求:
axios.get( '/axios-server' , {
//url引數
params:{
a:''
b:''
},
//請求頭資訊
headers:{
name:''
}
}).then(value =>{});
通過axios函式傳送請求(大體一致,就是將url和請求型別寫入物件中):
axios({
//type
method :'get'
//url
url:'axios-server' ,
//url引數
params:{
a:''
b:''
},
//請求頭資訊
headers:{
name:''
}
}).then(value =>{});
6.用fetch函式傳送Ajax請求(用的較少,瞭解就好)
fetch( 'url' , {
//type
method :'get'
//請求頭資訊
headers:{
name:''
}
//請求體
body:'username=123&password=123',
}).then(response=>{});
7.跨域
同源策略:
同源策略(Same-Origin Policy)最早由Netscape 公司提出,是瀏覽器的一種安全策略
同源: 協議、域名、埠號必須完全相同
跨域: 違背同源策略就是跨域
解決跨域1 JSONP(非官方):
在網頁有一些標籤天生具有跨域能力,比如:img link iframe script。JSONP 就是利用script 標籤的跨域能力來發送請求的。只支援 get 請求
示例:<script src="http://locahost:9000/jsonp-server" ></script>
http://localhost: + 埠號 + / + 請求資訊
解決跨域2 CORS(官方):
CORS(Cross-Origin Resource Sharing),跨域資源共享。CORS 是官方的跨域解決方案,它的特點是不需要在客戶端做任何特殊的操作,完全在伺服器中進行處理,支援get 和post 請求。跨域資源共享標準新增了一組HTTP 首部欄位,允許伺服器宣告哪些源站通過瀏覽器有許可權訪問哪些資源。CORS 是通過設定一個響應頭來告訴瀏覽器,該請求允許跨域,瀏覽器收到該響應以後就會對響應放行。
示例:response.setHeader('Access-Control-Allow-Origin','*')