> For the complete documentation index, see [llms.txt](https://docs.webmix.cc/ajax/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.webmix.cc/ajax/2.-ji-ben-guan-nian/2.1-tong-bu-yu-fei-tong-bu.md).

# 2.1 同步與非同步

## 什麼是 AJAX？

**AJAX** = **A**synchronous **J**avaScript **a**nd **X**ML

是一種非同步技術(**Asynchronous**)。早期在寫網頁的時候，尚不支援 AJAX 時，無法做到頁面**局部**更新資料這件事情，每次點擊連結，都一定是整個頁面重新整理。然而在有了 AJAX 技術之後，使得頁面局部更新內容，得以實現。

### 瞭解同步、非同步

同步(synchronous)：

```html
<!DOCTYPE html>
<html lang="zh-Hant">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <script>
      console.log("1");
      for(let i = 0; i < 100; i++){
        console.log("2");
      }
      console.log("3");
    </script>
  </body>
</html>
```

{% hint style="info" %}
先印出 1，然後印 100 次的 2，再印出 3，這就是同步(synchronous)的程式概念：一段程式執行之後 才會接續往下執行。
{% endhint %}

非同步(asynchronous)程式碼：

```html
<!DOCTYPE html>
<html lang="zh-Hant">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <script>
      console.log("1");
      
      setTimeout(function(){
        console.log("2");
      }, 1000);
      
      console.log("3");
    </script>
  </body>
</html>

```

{% hint style="info" %}
先印出 1，然後執行到 setTimeout 時，計時 1 秒鐘，在計時的期間，瀏覽器並不會停下來等，而是會繼續往下執行，所以會印出 3，然後計時的 1 秒鐘到了之後，且同步類型的程式碼也都執行完了，這時就會來執行 setTimout 所指定的 function 裡的程式。
{% endhint %}
