Ajax — 第三天
生活随笔
收集整理的這篇文章主要介紹了
Ajax — 第三天
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Ajax-03
模板引擎原理
正則回顧
- 區(qū)分正則方法和字符串方法
- 正則方法
- test()
- exec()
- 字符串方法
- match()
- replace()
- split()
- search()
- 正則方法
正則方法由正則表達(dá)式調(diào)用;字符串方法由字符串調(diào)用;
-
exec方法
- 功能:使用正則表達(dá)式匹配字符串,返回值中包含匹配的結(jié)果
- 特點:
- 一次只能匹配一個結(jié)果
- 再次調(diào)用將匹配下一個結(jié)果
- 沒有更多匹配則返回null
- 如果正則表達(dá)式中有捕獲(小括號),則返回值中包括捕獲的結(jié)果
-
replace方法
- 功能:字符串替換
- 特點:
- 可以使用正則表達(dá)式進(jìn)行匹配搜索
- 可以使用函數(shù)完成高級的替換
實現(xiàn)模板引擎
<script type="text/html" id="test"><p>{{title}}</p><p>{{content}}</p> </script><script>let data = {title: '錦瑟',content: '錦瑟無端五十弦,一弦一柱思華年。'}// 自定義函數(shù),實現(xiàn)模板引擎的功能。體會一下真實的模板引擎的實現(xiàn)原理function template (tplId, data) {// 1. 根據(jù)模板的id,找到元素,并獲取元素里面的HTMLlet html = document.getElementById(tplId).innerHTML;// console.log(html);// 2. 替換HTML中的 {{xxx}} 為真實的數(shù)據(jù)// html = html.replace('{{title}}', data.title);// html = html.replace('{{content}}', data.content);let reg = /{{(\w+)}}/g; // \w 表示大小寫字母、數(shù)字、下劃線let result = '';while (result = reg.exec(html)) {html = html.replace(result[0], data[result[1]]);}// 3. 將替換好的結(jié)果返回即可return html;}// 使用template函數(shù),完成模板引擎功能let str = template('test', data);console.log(str); </script>新聞列表案例
略,參見代碼
原生XHR對象
發(fā)送GET方式的請求
// 使用 xhr 對象發(fā)送GET方式的請求 /*1. 創(chuàng)建 xhr 對象2. 調(diào)用 xhr.open() 函數(shù)。設(shè)置請求方式和url3. 調(diào)用 xhr.send() 函數(shù)。發(fā)送請求4. 監(jiān)聽 xhr.onreadystatechange 事件。只要ajax的狀態(tài)改變就會觸發(fā)> 第4步,可以放到第3步或者第2步之前> ajax的狀態(tài),后續(xù)講解*/let xhr = new XMLHttpRequest(); xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks'); xhr.send(); xhr.onreadystatechange = function () {// console.log(111);// 這個事件觸發(fā)了多次,因為輸出看到,有三次結(jié)果// xhr.responseText; // 接收響應(yīng)結(jié)果if (xhr.readyState === 4) {console.log(xhr.responseText);} };Ajax的狀態(tài)
- 上圖中ajax的狀態(tài),一共有5個,分別用數(shù)字 0、1、2、3、4表示。
- 我們只需要關(guān)系最后一個狀態(tài)即可,因為此時,我們可以接收到完整的結(jié)果
- 代碼中,我們使用 xhr.readyState 屬性表示ajax的狀態(tài)
關(guān)于onreadystatechange事件的觸發(fā)時機:
- 很明顯的,ajax的狀態(tài)值發(fā)生了改變,比如從0變化到1、或者從1變化到2…的時候,會觸發(fā)
- 如果服務(wù)器返回大量的數(shù)據(jù),瀏覽器是分塊接收數(shù)據(jù)的,當(dāng)接收到的數(shù)據(jù)量發(fā)生變化的時候,也會觸發(fā)
xhr發(fā)送帶參數(shù)的GET請求
- GET方式的請求參數(shù),叫做查詢字符串,英文 querystring
- 查詢字符串的格式 key=value&key=value....
- 發(fā)送get請求的時候,查詢字符串和接口之間,使用 ? 隔開
之前,$.ajax里面的請求參數(shù),之所以可以寫對象形式,是因為函數(shù)內(nèi)部,把對象轉(zhuǎn)成了查詢字符串格式。
xhr發(fā)起POST方式的請求
和GET方式的兩個區(qū)別:
- 必須在open和send之間,加一個請求頭
- 查詢字符串的位置變化為send的參數(shù)
URL編碼
// 編碼 encodeURI('紅&黑'); // "%E7%BA%A2&%E9%BB%91" encodeURIComponent('紅&黑'); // "%E7%BA%A2%26%E9%BB%91"// 解碼 decodeURI('%E7%BA%A2&%E9%BB%91'); // "紅&黑" decodeURIComponent("%E7%BA%A2%26%E9%BB%91"); // "紅&黑"在實際開發(fā)中,需要對中文及需要編碼的特殊符號進(jìn)行編碼:
使用的編碼函數(shù):
- encodeURI() — 能夠?qū)χ形倪M(jìn)行編碼
- encodeURIComponent() — 能夠?qū)χ形暮吞厥夥栠M(jìn)行編碼(&=)
封裝
思路:
- 模擬jQuery中的 $.ajax()
步驟:
定義與調(diào)用函數(shù)
// 模擬 $.ajax() ,自己封裝一個實現(xiàn)ajax請求的函數(shù)/*option 是一個對象option.type 表示請求類型option.url 表示請求的urloption.data 表示請求參數(shù)option.success() 表示一個處理服務(wù)器返回結(jié)果的函數(shù)*/ function ajax (option) {}// 調(diào)用函數(shù) ajax({type: 'post', // GET或POSTurl: 'http://www.liulongbin.top:3006/api/addbook',data: {bookname: 'aaa', author: 'bbb', publisher: 'ccc'},success: function (res) {console.log(res);} });寫基本的代碼
function ajax (option) {let xhr = new XMLHttpRequest();xhr.onreadystatechange = function () {}xhr.open();xhr.send(); }將服務(wù)器返回的結(jié)果傳遞給success
function ajax (option) {let xhr = new XMLHttpRequest();xhr.onreadystatechange = function () {if (this.readyState === 4 && this.status === 200) {let x = JSON.parse(this.responseText);option.success(x); // 調(diào)用success函數(shù),把服務(wù)器返回的結(jié)果傳遞給它}}xhr.open();xhr.send(); }針對GET和POST分別寫open和send方法
function ajax (option) {let xhr = new XMLHttpRequest();xhr.onreadystatechange = function () {if (this.readyState === 4 && this.status === 200) {let x = JSON.parse(this.responseText);option.success(x); // 調(diào)用success函數(shù),把服務(wù)器返回的結(jié)果傳遞給它}}// 判斷,GET和POST方式單獨完成if (option.type === 'GET') {xhr.open('GET', option.url);xhr.send();} else if (option.type === 'POST') {xhr.open('POST', option.url);xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');xhr.send();} }將對象形式的data處理成querystring
function ajax (option) {let xhr = new XMLHttpRequest();xhr.onreadystatechange = function () {if (this.readyState === 4 && this.status === 200) {let x = JSON.parse(this.responseText);option.success(x); // 調(diào)用success函數(shù),把服務(wù)器返回的結(jié)果傳遞給它}}// 先處理查詢字符串,把傳遞進(jìn)來的 對象形式的data,處理成查詢字符串格式// {bookname: 'aaa', author: 'bbb', publisher: 'ccc'}// ===> bookname=aaa&author=bbb&publiser=ccclet arr = [];for (let key in option.data) {// key 表示對象的 鍵// option.data[key] 表示對象的值// arr.push('key=value');arr.push(key + '=' + option.data[key]); // ['bookname=aaa', 'author=bbb', ...]}let querystring = arr.join('&'); // bookname=aaa&author=bbb&publiser=ccc// 判斷,GET和POST方式單獨完成if (option.type === 'GET') {xhr.open('GET', option.url + '?' + querystring);xhr.send();} else if (option.type === 'POST') {xhr.open('POST', option.url);xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');xhr.send(querystring);} }優(yōu)化-請求方式不區(qū)分大小寫
function ajax (option) {let xhr = new XMLHttpRequest();xhr.onreadystatechange = function () {if (this.readyState === 4 && this.status === 200) {let x = JSON.parse(this.responseText);option.success(x); // 調(diào)用success函數(shù),把服務(wù)器返回的結(jié)果傳遞給它}}// 先處理查詢字符串,把傳遞進(jìn)來的 對象形式的data,處理成查詢字符串格式// {bookname: 'aaa', author: 'bbb', publisher: 'ccc'}// ===> bookname=aaa&author=bbb&publiser=ccclet arr = [];for (let key in option.data) {// key 表示對象的 鍵// option.data[key] 表示對象的值// arr.push('key=value');arr.push(key + '=' + option.data[key]); // ['bookname=aaa', 'author=bbb', ...]}let querystring = arr.join('&'); // bookname=aaa&author=bbb&publiser=ccc// 定義變量,接收并處理請求方式let method = option.type.toUpperCase(); // 把請求方式轉(zhuǎn)成大寫// 判斷,GET和POST方式單獨完成if (method === 'GET') {xhr.open('GET', option.url + '?' + querystring);xhr.send();} else if (method === 'POST') {xhr.open('POST', option.url);xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');xhr.send(querystring);} }總結(jié)
以上是生活随笔為你收集整理的Ajax — 第三天的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Ajax — 聊天机器人演示
- 下一篇: Ajax — 新闻列表