# What are the advantages and disadvantages of using Ajax?
## AJAX (Asynchronous JavaScript And XML)
> AJAX的工作原理
>
> Ajax的工作原理相當於在用戶和伺服器之間加了—個中間層(AJAX引擎),使用戶操作與伺服器響應異步化。並不是所有的用戶請求都提交給伺服器,像—些數據驗證和數據處理等都交給Ajax引擎自己來做, 只有確定需要從伺服器讀取新數據時再由Ajax引擎代為向伺服器提交請求。
>
> Ajax其核心有JavaScript、XMLHTTPRequest、DOM對象組成,通過XmlHttpRequest對象來向伺服器發異步請求,從伺服器獲得數據,然後用JavaScript來操作DOM而更新頁面。這其中最關鍵的一步就是從伺服器獲得請求數據。讓我們來了解這幾個對象
### 優點
1. 不會重新載入網頁
* 跟伺服器互動時不會重新載入整個頁面,Ajax會在頁面上局部刷新,減少使用者實際和心裡等待的時間,提高使用者體驗。
2. 減輕伺服器的負擔,加快瀏覽速度
* 透過 AJAX 技術,**依照用戶的需要**從伺服器獲取部分數據(json/XML..檔),不是整個頁面(html),可以大大減少不必要的請求和回應的資料料,減輕伺服器負擔,提高瀏覽速度。
* 把傳統網站一些伺服器負擔的工作轉嫁到客戶端,利用客戶端閒置的能力來處理,減輕伺服器和頻寬的負擔,節約空間和寬頻租用成本。並且減輕伺服器的負擔,ajax的原則是“**按需取資料**”,可以最大程度的減少冗餘請求,和響應對伺服器造成的負擔。
3. 非同步(Asynchronous Request)請求與伺服器互動
* 非同步會在背後運作,不會打斷使用者的操作,具有更加迅速的響應能力。
* 
4. 基於標準化並被廣泛支持的技術,不需要下載插件或小程序
* 目前大部分的瀏覽器都支持Ajax技術,使得它推廣十分順暢,但需要客戶允許JavaScript在瀏覽器上執行。
### 缺點
1. 沒有瀏覽器的History和BACK功能
* 因為頁面是使用AJAX動態的更新資料,都在同一個頁面,使用者沒辦法使用上一頁下一頁給切換頁面。
2. 違背了url和資源定位的初衷,動態頁面很難被收藏。
* 假如今天兩個使用者使用同一個url同一個頁面,但兩個人看到的內容可能是不同的。
* 或者今天你想要收藏一個url,收藏到的頁面可能不是你當下看到的頁面資訊。
3. 對搜尋引擎的支援比較弱。
“… as long as you’re not blocking Googlebot from crawling your JavaScript or CSS files, we are generally able to render and understand your web pages like modern browsers.”
[Google Search Central - JavaScript SEO-Use the History API instead of fragments](https://developers.google.com/search/docs/advanced/javascript/javascript-seo-basics)
使用 History API 增加路徑,確保Googlebot可以找到相對應的路徑。
For single-page applications with client-side routing, use the History API to implement routing between different views of your web app. To ensure that Googlebot can find links, avoid using fragments to load different page content. The following example is a bad practice, because Googlebot will not crawl the links:
```*
<nav>
<ul>
<li><a href="#/products">Our products</a></li>
<li><a href="#/services">Our services</a></li>
</ul>
</nav>
<h1>Welcome to example.com!</h1>
<div id="placeholder">
<p>Learn more about <a href="#/products">our products</a> and <a href="#/services">our services</p>
</div>
<script>
window.addEventListener('hashchange', function goToPage() {
// this function loads different content based on the current URL fragment
const pageToLoad = window.location.hash.slice(1); // URL fragment
document.getElementById('placeholder').innerHTML = load(pageToLoad);
});
</script>
```
Instead, you can make sure link URLs are accessible to Googlebot by implementing the History API:
```*
<nav>
<ul>
<li><a href="/products">Our products</a></li>
<li><a href="/services">Our services</a></li>
</ul>
</nav>
<h1>Welcome to example.com!</h1>
<div id="placeholder">
<p>Learn more about <a href="/products">our products</a> and <a href="/services">our services</p>
</div>
<script>
function goToPage(event) {
event.preventDefault(); // stop the browser from navigating to the destination URL.
const hrefUrl = event.target.getAttribute('href');
const pageToLoad = hrefUrl.slice(1); // remove the leading slash
document.getElementById('placeholder').innerHTML = load(pageToLoad);
window.history.pushState({}, window.title, hrefUrl) // Update URL as well as browser history.
}
// Enable client-side routing for all links on the page
document.querySelectorAll('a').forEach(link => link.addEventListener('click', goToPage));
</script>
```
4. AJAX的安全問題。
* Ajax技術就如同對企業數據建立了一個直接通道。這使得開發者在不經意間會暴露比以前更多的數據和伺服器邏輯。Ajax難以避免一些已知的安全弱點,諸如跨站點腳步攻擊、SQL注入攻擊和基於Credentials的安全漏洞等等。
* Ajax技術的確讓駭客更有機會透過XSS的手法侵害使用者,不過XSS之所以能成功,通常是網站本身已經存在資安防線上的漏洞,例如沒有檢查使用者上傳的資料,或是應用程式、系統本身有漏洞,如果能做好這些資安防護,那麼即使採用再多的Ajax功能,使用者一樣安全無虞。
參考連結:
[使用Ajax的網頁安全性](https://ithelp.ithome.com.tw/articles/10000126)
開發Ajax的10大守則
1.前、端後都要做好安全的把關工作
2.盡量以HTTP POST方法傳輸資料
3.不要直接用eval函式喚起JSON物件 (eval函式會將傳入的字串當做 JavaScript 代碼進行執行。)
4.限制使用者可用的HTML語法
5.禁止可留言的網頁頁面使用JavaScript語法 >>>
5. 任何瀏覽器或移動設備中的瀏覽器不支持 JavaScript 或 XMLHttpRequest 或禁用此功能的用戶沒辦法正確獲取Ajax的動態頁面。

[上圖參考連結](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)
### 結論:解決方案:
History API,透過pushState()、replaceState()的方式更新URL,以及 history.go()、history.back()、來切換頁面上下路徑,同時提供State物件讓開發者存取每一頁的狀態。
[Is AJAX Bad for SEO? Not Necessarily. Here’s Why.](https://prerender.io/ajax-seo/)
[操控瀏覽器歷史紀錄](https://developer.mozilla.org/zh-TW/docs/Web/API/History_API)
[凡走過請留下痕跡:AJAX網頁的狀態與瀏覽記錄](http://rettamkrad.blogspot.com/2013/04/ajaxandhistoryapi.html)
參考連結:
[什麼是 Ajax? 搞懂非同步請求 (Asynchronous request)概念](https://tw.alphacamp.co/blog/ajax-asynchronous-request)
[Ajax原理以及優缺點](https://newgoodlooking.pixnet.net/blog/post/125525541)
[Pros and Cons of AJAX](https://dzone.com/articles/pros-and-cons-of-ajax)
[面試分享|前端Ajax技術原理](https://kknews.cc/tech/3o6nky.html)
[AJAX請求真的不安全麼?談談Web安全與AJAX的關係](https://kknews.cc/zh-tw/code/8xaeype.html)