# Ajax、API串接與跨來源處理 ###### tags: `Ajax` --- 原文網址:[輕鬆理解 Ajax 與跨來源請求](https://blog.techbridge.cc/2017/05/20/api-ajax-cors-and-jsonp/) Ajax也俗稱API串接,目的是取得資料,可以從不同網域或是後端取得資料。 通常串接API會使用非同步處理js,例如: 當非同步的操作完成時,就可以呼叫這個 Function,並且把資料帶進來。 ```htmlmixed= // 假設有個發送 Request 的函式叫做 sendRequest sendRequest('https://api.twitch.tv/kraken/games/top?client_id=xxx', callMe); function callMe (response) { console.log(response); } // 或者寫成匿名函式 sendRequest('https://api.twitch.tv/kraken/games/top?client_id=xxx', function (response) { console.log(response); }); ``` 要發送 Request 的話,就要透過瀏覽器幫我們準備好的一個物件,叫做XMLHttpRequest,範例程式碼如下: ```htmlmixed= var request = new XMLHttpRequest(); request.open('GET', `https://api.twitch.tv/kraken/games/top?client_id=xxx`, true); request.onload = function() { if (request.status >= 200 && request.status < 400) { // Success! console.log(request.responseText); } }; request.send(); ``` ## CORS 可以跨域 Domain 的API串接方式 Header 裡面必須加上<span class="code1">Access-Control-Allow-Origin</span> ## JSONP 利用<script>達到跨域的請求 ```htmlmixed= <script> receiveData({ data: 'test' }); </script> <script> function receiveData (response) { console.log(response); } </script> ``` ## 利用 JSONP,也可以存取跨來源的資料。但 JSONP 的缺點就是你要帶的那些參數永遠都只能用附加在網址上的方式(GET)帶過去,沒辦法用 POST。 ### 如果能用 CORS 的話,還是應該優先考慮 CORS。 --- <span class="code1"></span> <style> h2 { color: #2383B8; } h3 { color: #1AA340; } h4 { color: white; background-color: #2383B8; padding:8px; } .code1 { padding: 2px 4px; font-size: 90%; color: #c7254e; background-color: #f9f2f4; border-radius: 4px; font-family:'Fira Code'; } .code { padding: 2px 4px; font-size: 90%; font-family:'Fira Code'; } </style>
×
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