###### tags:`AJAX`
# AJAX - 2.同步&非同步
承上一章節[AJAX - 1.透過 XMLHttpRequest 物件跨瀏覽器撈資料](https://hackmd.io/PsadAflPS06tkDqwXr0YPA?both)
`變數(自取名).open('','',true)`
自訂code參考
`NEWAJAX.open('get','https://hexschool.github.io/ajaxHomework/data.json',true);`
**true**:非同步.**false**:同步
### 非同步
這裡我們在打一段語法,測試撈到資料,發現沒有撈到任何資料,但是上一章節可以看到已經有連接到json資料

<span style="color:red"><b>true非同步</b>不會等資料傳回來,就讓程式繼續往下跑,等到回傳才會自動回傳.</span>
<span style="color:red"><b>fasle:同步</b>等資料傳回來,才會讓程式繼續往下去跑</span>
### 同步
將true改成flase,在重新跑一次,可以發現撈到responseText資料
```
var NEWAJAX = new XMLHttpRequest();
NEWAJAX.open('get','https://hexschool.github.io/ajaxHomework/data.json',true);
NEWAJAX.send(null);
console.log(NEWAJAX.responseText);
```

<p style="color:red">大部分時候都使用true非同步,包括像是使用Vue,React等框架,因為資料量龐大時不可能等資料loading完</p>
### onload被動等資料載入完後才觸發
在true非同步情況下,如何撈資料並在製呢?這邊使用onload語法.被動等資料載入完後再作業,可以發現chorm console可以撈到資料
```
var NEWAJAX = new XMLHttpRequest();
NEWAJAX.open('get','https://hexschool.github.io/ajaxHomework/data.json',true);
NEWAJAX.send(null);
NEWAJAX.onload = function(){
console.log(NEWAJAX.responseText);
}
```

### onload情況下,抓資料傳送到網頁畫面
```
//html
<div class="message"></div>
//js
var NEWAJAX = new XMLHttpRequest();
NEWAJAX.open('get','https://hexschool.github.io/ajaxHomework/data.json',true);
NEWAJAX.send(null);
NEWAJAX.onload = function(){
console.log(NEWAJAX.responseText);
var str = JSON.parse(NEWAJAX.responseText);
document.querySelector('.message').textContent = str[0].name
}
```

**整個流程為**
1.建立一個XMLHttpRequest
2.傳送到對方伺服器要資料
3.回傳資料到自己的瀏覽器
4.拿到資料後再看看怎樣處理