我們來捋一下Ajax的概念,JS語言是單執行緒的語言、異步與同步,
JS是一門單執行緒的語言,所以JS語言寫出來的程式也是單執行緒的程式,
學習ajax首先需要了解在編程中的異步與同步的概念,
異步和同步
-
同步:程式發出請求需要等待當前請求執行結束才能進行下一步的操作,
-
異步:程式發出請求不需要等待當前請求結束就能進行下一步的操作,
ajax的實作
我們要完成一個基本的ajax互動操作只需要四步即可,
-
創建異步物件:
let xhr = new XMLHttpRequest();
-
指定請求的方式/埠/檔案:
xhr.open('get','./a.txt',true);
-
發送請求:
xhr.send();
-
異步物件監聽狀態的變化(通過狀態碼):
xhr.addEventListener('readystatechange',function(e){
if( xhr.readyState == 4 ){
console.log(xhr.responseText);
}
} ,false);
0:請求為初始化
1:服務器連接已建立
2:請求已接收
3:請求處理中
4:請求已完成,且回應已就緒
這是最基本的實作,然后接下來進行對ajax的封裝,使用es5和es6的兩種方式進行面向物件的封裝:
<script>
let a = new ajax({
url:"./../地址",// 必填
method:"post",// 選填
data:"資料" // 這是 引數
//相當于 物件引數的一樣的引數
}).then(function(data){
// data就是后臺回應回來的資料
console.log(data)
})
</script>
es5的方式
function ajax(options){
// 初始化資料
this.url = options.url
this.method = options.method || "get"
this.data = options.data || {}
// 創建xhr
this.xhr = new XMLHttpRequest()
if( this.method === "get" ){// get
this.get()
}else{// post
this.post()
}
}
// 建構式原型上的屬性和方法將來都可以被該建構式下所創建的物件所共有
ajax.prototype.get = function(){
// 物件的方法 this 指向了物件本身
this.xhr.open("get",this.url+"?"+this.data,true)
this.xhr.send()
}
ajax.prototype.post = function(){
// 物件的方法 this 指向了物件本身
this.xhr.open("post",this.url)
this.xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
this.xhr.send(this.data)
}
ajax.prototype.then = function(fn){
this.xhr.onreadystatechange = function(){
// this指向了事件的觸發者, a.xhr
if( this.readyState === 4 && this.status === 200 ){
fn(this.responseText)
}
}
}
es6的方式:
class ajax{
constructor(options){
// 物件的解構賦值
let{ method="get",url,data="" } = options
// 創建xhr
this.xhr = new XMLHttpRequest()
// 判斷
if( method === "get" ){
this.get(url,data)
}else{
this.post(url,data)
}
}
// 在ES6的class類中的寫法,原型上的方法是和構造器同級的
get(url,data){
this.xhr.open("get",url+"?"+data,true)
this.xhr.send()
}
post(url,data){
this.xhr.open("post",url,true)
this.xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
this.xhr.send(data)
}
then(fn){
this.xhr.onreadystatechange = ()=>{
if( this.xhr.readyState === 4 && this.xhr.status === 200 ){
fn(this.xhr.responseText)
}
}
}
}
感謝關注!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/189022.html
標籤:java
上一篇:vue 監聽表單變化
