Web前端-Ajax基礎技術(下)

Web前端-Ajax基礎技術(下)
Web前端-Ajax基礎技術(下)
你要明白 ajax
是什麼,怎麼使用?
ajax
, web
程式是將資訊放入公共的伺服器,讓所有網路使用者可以通過瀏覽器進行訪問。
瀏覽器傳送請求,獲取伺服器的資料:
位址列輸入地址,表單提交,特定的 href
或 src
屬性。
<script> var xhr = new XMLHttpRequest(); xhr.open('GET', 'test.php'); xhr.send() xhr.onreadystatechange = function() { if(this.readyState != 4) return var res = JSON.parse(this.responseText); // res 伺服器返回的資料 var data = res.data; for(var i = 0; i<data.length; i++){ } }
ajax
上手:
// 建立一個XMLHttpRequest型別的物件 var xhr = new XMLHttpRequest(); // 開啟一個網址的連線 xhr.open('GET', './time.php'); // 傳送一次請求 xhr.send(null); // 處理網頁呈現後的操作 xhr.onreadystatechange = function() { if(this.readyState === 4) { console.log(this); } }

效果
readyState
0 xhr被建立,未呼叫open()方法 1 open()方法被呼叫,建立了連線 2 send()方法被呼叫,可以獲取狀態行和響應頭 3 響應體下載中,responseTest屬性可能已經包含部分資料 4 響應體下載完成,直接使用responseText
http
請求:
// 設定請求報文的請求行 xhr.open('GET', './time.php'); // 設定請求頭 xhr.setRequestHeader('Accept', 'text/plain'); // 設定請求體 xhr.send(null); xhr.onreadystatechange = function() { if(this.readyState === 4) { // 獲取響應狀態碼 console.log(this.status); // 獲取響應狀態描述 console.log(this.statusText); // 獲取響應頭資訊 console.log(this.getResponseHeader('Content-Type')); // 指定響應頭 console.log(this.getAllResponeseHeaders()); // 全部響應頭 // 獲取響應體 console.log(this.responseText) // 文字形式 console.log(this.responseXML) // xml } }
post
請求:
var xhr = new XMLHttpRequest(); // open方法的第一個引數作用, 設定請求的method xhr.open('POST', './add.php'); // 設定請求體格式 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send('key=value'); xhr.onreadystatechange = function() { if(this.readyState === 4) { console.log(this.responseText); } }
非同步同步:
// 非同步 console.log('before ajax'); var xhr = new XMLHttpRequest(); xhr.open('GET', './time.php', true); xhr.send(null); xhr.onreadystatechange = function() { if(this.readyState === 4){ console.log('request done'); } } console.log('after ajax'); // 同步 console.log('before ajax'); var xhr = new XMLHttpRequest(); xhr.open('GET', './time.php', false); xhr.send(null); xhr.onreadystatechange = function() { if(this.readyState === 4){ console.log('request done'); } } xhr.send(null); console.log('after ajax');
響應型別:
var xhr = new XMLHttpRequest(); xhr.open('GET', 'test.php'); xhr.send(); // 請求代理物件,響應型別 xhr.responseType = 'json'; xhr.onreadystatechange = function() { if(this.readyState != 4) return; console.log(this); }
伺服器響應,使用 XMLHttpRequest
物件的 responseText
或 responseXML
屬性。
responseText
獲取字串形式的響應資料, responseXML
獲取 xml
形式的響應資料。
responseText
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
模板引擎:
artTemplate: https://aui.github.io/art-template/
art-template
是一個簡約,超快的模板引擎,採用作用域宣告的技術來優化模板渲染速度。
安裝:
npm install art-template --save
下載:
lib/template-web.js
<script src="template-web.js" > </script>
// 封裝 function ajax(method, url, params) { var xhr = new XMLHttpRequest(); xhr.open(method, url); xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); params = params || null; xhr.send(params); xhr.onreadystatechange=function(){ if(this.readyState != 4) return console.log(this.responseText); } } ajax('GET', 'time.php', 'key=value'); function ajax(method, url, params) { var xhr = new XMLHttpRequest(); if(method === 'GET'){ url += "?" + params; } xhr.open(method, url); var data = null; if(method === 'POST') { xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); data = params } xhr.send(data); xhr.onreadystatechange=function(){ if(this.readyState != 4) return console.log(this.responseText); } }
// 傳物件 function ajax(method, url, params) { var xhr = new XMLHttpRequest(); if(typeof params === 'object'){ var tempArr = []; for(var key in params){ var value = params[key]; tempArr.push(key + "=" + value); } params = tempArr.join('&'); } if(method === 'GET'){ url += "?" + params; } xhr.open(method, url); var data = null; if(method === 'POST') { xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); data = params } xhr.send(data); xhr.onreadystatechange=function(){ if(this.readyState != 4) return console.log(this.responseText); } }
function ajax(method, url, params, done) { method = method.toUpperCase(); var xhr = new XMLHttpRequest(); if(typeof params === 'object'){ var tempArr = []; for(var key in params){ var value = params[key]; tempArr.push(key + "=" + value); } params = tempArr.join('&'); } if(method === 'GET'){ url += "?" + params; } xhr.open(method, url, false); var data = null; if(method === 'POST') { xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); data = params } xhr.onreadystatechange=function(){ if(this.readyState != 4) return // console.log(this.responseText); done(this.responseText); } xhr.send(data); } var ondone = function(res) { console.log(res); }
回撥:

效果
<script> function foo() { setTimeout(function(){ return Date.now(); }, 1000); } var time = foo() </script>
jquery
中的 ajax
。
https://www.jquery123.com/category/ajax/
function ajax(method, url, params, done) { // 統一轉換大寫 method = method.toUpperCase(); // urlencoded var pairs = []; for(var key in params) { pairs.push(key+"="+params[key]); } var querystring = pairs.join('&'); var xhr = window.XMLHttpRequest?new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); xhr.addEventListener('readystatechange',function(){ } }
<script src="jquery.js"></script> <script> $.ajax('./time.php', { type: 'post', // method 請求方法 success: function(res) { console.log(res); } } </script> $.ajax({ url: 'time.php', type: 'post', data: { id: 1, name: '張三' }, success: function(res) { console.log(res); } })
$.ajax({ url: 'json.php', type: 'get', dataType: 'json', success: function(res) { console.log(res) } })
ajax
回撥事件:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script src="jquery.js"></script> <script> $.ajax({ url: 'time.php', type: 'get', beforeSend: function(xhr) { console.log('beforeSend', xhr); }, success: function(res) { console.log(res); }, error: function(xhr) { console.log(xhr); }, complete: function(xhr) { console.log(xhr); } }) </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script src="jquery.js"></script> <script> var xhr = new XMLHttpRequest(); xhr.open('get','time.php'); xhr.send() xhr.onreadystatechange = function() { if(this.readyState != 4) return console.log(this.responseText); } </script> </body> </html>
<script src="jquery.js"></script> <script> $.get('time.php', function(res){ console.log(res); }) $.get('time.php', { id: 1 }, function(res) { console.log(res); }) $.post('time.php', { id: 1 }, function(res) { console.log(res); }) </script>
.ajaxComplete() 當ajax請求完成後註冊一個回撥函式 .ajaxError() ajax請求出錯 .ajaxSend() ajax請求傳送之前繫結一個要執行的函式 .ajaxStart() 在ajax請求剛開始時執行一個處理函式 .ajaxStop() 在ajax請求完成時執行一個處理函式 .ajaxSuccess() 繫結一個函式當ajax請求成功完成時執行 jQuery.ajax() 執行一個非同步的http(ajax)請求 jQuery.ajaxPerfilter() 在每個請求之前被髮送和$.ajax()處理它們前處理 jQuery.ajaxSetup() 為以後要用到的ajax請求設定預設的值 jQuery.ajaxTransport() 建立一個物件 jQuery.get() 使用一個http get請求從伺服器載入資料 jQuery.getJSON() jQuery.getScript() GET請求從伺服器載入並執行一個 JavaScript 檔案 jQuery.post() 請求從伺服器載入資料
跨域:
同源,域名,協議,埠,完全相同,同源的相互通過 ajax
的方式進行請求。
不同源地址之間,不能相互發送 ajax
請求。
$.get('http://', function(res) { console.log(res); })
<!DOCTYPE html> <head> <meta charset = "UTF-8"> <title>AJAX基礎回顧</title> </head> <body> <script> var xhr = new XMLHttpRequest(); xhr.open('GET', 'test.php'); xhr.responseType='json'; xhr.onreadystatechange = function() { if(this.readyState !== 4) return console.log(this.response); } </script> </body> </html>
$.get('http://...', function(res){ console.log(res); })
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"/> <meta http-equiv="Content-Language" content="zh-cn"/> <meta name="robots" content="all"/> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"/>
var link = document.createElement('link'); link.rel = 'stylesheet'; link.href = 'http//...'; document.body.appendChild(link); var script = document.createElement('script'); script.src = 'http://...'; document.body.appendChild(script);
jsonp
原理:
json
是藉助 script
標籤傳送跨域請求的技巧。
原理是在客戶端藉助 script
標籤請求服務端的一個動態網頁,服務端的這個動態網頁返回一段帶有函式呼叫的 javascript
全域性函式呼叫的指令碼,將原本需要返回給客戶端的資料傳遞進去。
$.ajax({ url: 'http://...', dataType: 'json', success: function(res) { console.log(res); } })
結言
好了,歡迎在留言區留言,與大家分享你的經驗和心得。
感謝你學習今天的內容,如果你覺得這篇文章對你有幫助的話,也歡迎把它分享給更多的朋友,感謝。
作者簡介
達叔,理工男,簡書作者&全棧工程師,感性理性兼備的寫作者,個人獨立開發者,我相信你也可以!閱讀他的文章,會上癮!,幫你成為更好的自己。長按下方二維碼可關注,歡迎分享,置頂尤佳。

努力努力再努力Jeskson