了解 AJAX 非同步觀念


Posted by hoyi-23 on 2021-05-23

延續上一個 筆記的內容

參考 CodePen範例

上一個筆記中,成功撈取資料了。
現在使用console.log來確認一下。
卻發現是空的?

為甚麼沒有撈到呢? 這邊就要來看同步與非同步觀念。


非同步 true

xhr.open('格式','網址',true);

true 指的是非同步,不會等資料傳回來,就讓程式繼續往下跑,等到回傳後才回自動傳回去。

同步 false

等資料傳回來程式才會往下跑console.log(xhr.responseText);


要使用true 還是 false?

大部分時候因為檔案大,若要等資料全部回傳後再繼續執行,會造成使用者體驗不佳。
通常會使用true非同步。


如何讓非同步正確撈到資料?


上圖顯示,因為使用非同步,所以在還沒有撈到資料前,就已經執行了console.log(xhr.responseText);,所以顯示不出來,該如何設定讓他在正確取得資料後,才執行呢?
我們可以利用onload

onload 在確定資料回傳後,才會執行。

xhr.onload = function(){
    console.log(xhr.responseText)
}


處理回傳後的資料

JSON資料回傳後會變成字串,我們可以使用JSON.parse(),將他轉換成陣列格式。

xhr.onload = function(){
    console.log(xhr.responseText)
    var str = JSON.parse(xhr.responseText)
}

將資料帶入到HTML內

xhr.onload = function(){
    console.log(xhr.responseText);
    var str = JSON.parse(xhr.responseText);
    document.querySelector('.message').textContent = str[0].name;
}


AJAX 步驟統整

  1. 建立一個物件 XMLHttpRequest()
  2. 傳送需求到對方伺服器 xhr.open()
  3. 回傳資料到自己的瀏覽器 xhr.send()
  4. 處理資料 xhr.onload

#ajax #同步與非同步







Related Posts

30-Day LeetCoding Challenge 2020 April Week 5 || Leetcode 解題

30-Day LeetCoding Challenge 2020 April Week 5 || Leetcode 解題

滑動到看不見某個元件,另一個就會元件出現的效果

滑動到看不見某個元件,另一個就會元件出現的效果

Create a role when first starting up the PostgreSQL DB

Create a role when first starting up the PostgreSQL DB


Comments