###### tags: `學習` `AJAX` `axios` {%hackmd BJrTq20hE %} # axios是甚麼? axios是一個套件可以用來簡化XMLHttpRequest的一個套件 以下是XMLHttpRequest取的資料的範例 ```javascript= let xhr = new XMLHttpRequest() xhr.open('get','[取得資料的網址](https://hexschool.github.io/ajaxHomework/data.json)',true) xhr.sned(null) xhr.onload = functoin(){ console.log(xhr.responseText) } ``` [XMLHttpRequest範例](https://codepen.io/efzdamnp-the-lessful/pen/gORezaP?editors=1011) 一共使用了6行程式碼 接著來看看axios ```javascript= axios.get('https://hexschool.github.io/ajaxHomework/data.json'). then(function(response){console.log(response.data) }) ``` 一共使用了3行程式碼就把東西給撈回來 [axios範例](https://codepen.io/efzdamnp-the-lessful/pen/rNzWvMx?editors=1011) ## 要如何使用axios呢? 推薦使用axios的cdn,不用安裝而且使用快速 [axios套件連接](https://github.com/axios/axios) 1.點選上面的連結後 複製有CDN的任意一行程式碼如下圖  2.把程式碼貼到 自己的js載入前如下圖  3.用chrom打開載入axios的網頁,按f12,點選console後輸入console.log(axios);如果由成功載入就會出現如下圖的內容。  ## 非同步觀念 先看看下面撈資料並用console.log()顯示資料的範例 ```javascript= let result =''; axios.get('https://hexschool.github.io/ajaxHomework/data.json'). then(function(response){console.log(response.data[0].name+'撈回來的資料') result = response.data[0].name }) console.log(result+'result內的資料') ``` [axios非同步範](https://codepen.io/efzdamnp-the-lessful/pen/xxLgZjd?editors=1111) 結果如下圖  會發現怎麼明明有撈到資料,為甚麼result會沒資料 原因是axios在執行的時候需要等待伺服器回傳資料,這個時候就會繼續往下執行程式碼,因為往下執行程式碼的時候資料來沒撈回來,所以result自然是空的 ## 要如何處理非同步呢? 那該怎麼辦呢??可以使用以下範例解決 ```javascript= let result =''; axios.get('https://hexschool.github.io/ajaxHomework/data.json'). then(function(response){console.log(response.data[0].name+'撈回來的資料') result = response.data[0].name renderData() }) function renderData(){ console.log(result+'result內的資料') } ``` 結果如下圖  另外寫一個函式,先註冊在chorm中,等到資料撈回來的時候再呼叫函式執行,就可處理非同步的問題了
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up