# JSON APIs and Ajax > [TOC] * **A**pplication **P**rogramming **I**nterface * Send and receive data * **A**synchronous **J**avaScript **A**nd **X**ML * A group of technologies * Make asynchronous requests to a server to transfer data, then load any returned data into the page * The browser does'nt stop loading a page to wait for the server's response * Also, the browser inserts updated data into part of the page without having to refresh the entire page > 可與伺服器進行非同步更新,不需要重新載入整個網頁 > 規劃一個網頁含有AJAX技術 > 最常見的例子就是 用戶註冊、驗證信箱,驗證信箱或用戶名是否有被重複使用,不用等到全部填完資料才能驗證 * **J**ava**S**cript **O**bject **N**otation * A kind of format ## Handle event * make to execute only once page has finished loading ```javascript= document.addEventListener('DOMContentLoaded', function(){ }); ``` * some examples ```javascript= document.getElementById('getMessage').onclick = function(){}; document.getElementsByClassName('message')[0].textContent="Here is the message"; ``` ## Get JSON * javascript notation ``` [ ] -> Square brackets represent an array { } -> Curly brackets represent an object " " -> Double quotes represent a string. They are also used for key names in JSON. ``` * JSON * key-value pairs * Transmitted in **bytes**, but applications recieves them as **string** ### JavaScript XMLHttpRequest Method * `.open(method, URL, asynchronous request)` * initialize th e request * `JSON.stringify()` * convert the JavaScript object into a string ```javascript= const req = new XMLHttpRequest(); req.open("GET",'/json/cats.json',true); //method, the URL of the API you are requesting data from, asynchronous request req.send(); //send the request req.onload = function(){ const json = JSON.parse(req.responseText); document.getElementsByClassName('message')[0].innerHTML = JSON.stringify(json); }; ``` * POST ```javascript= const xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 201){ const serverResponse = JSON.parse(xhr.response); document.getElementsByClassName('message')[0].textContent = serverResponse.userName + serverResponse.suffix; } }; const body = JSON.stringify({ userName: userName, suffix: ' loves cats!' }); xhr.send(body); ``` ### `fetch()` method * `fetch()` * returns a [Promise](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Promise) > Promise 物件代表一個即將完成、或失敗的非同步操作,以及它所產生的值 > [How to use Promise](https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Using_promises) ```javascript= fetch('/json/cats.json') .then(response => response.json()) .then(data => { document.getElementById('message').innerHTML = JSON.stringify(data); }) ``` * some full example * XMLHttp request method ```javascript= <script> document.addEventListener('DOMContentLoaded', function(){ document.getElementById('getMessage').onclick = function(){ const req = new XMLHttpRequest(); req.open("GET", '/json/cats.json', true); req.send(); req.onload = function(){ const json = JSON.parse(req.responseText); document.getElementsByClassName("message")[0].innerHTML = (JSON.stringify(json)); } }; }); </script> ``` * `fetch()` method ```javascript= <script> document.addEventListener('DOMContentLoaded',function(){ document.getElementById('getMessage').onclick= () => { fetch('/json/cats.json') .then(response => response.json()) .then(data => { document.getElementById('message').innerHTML = JSON.stringify(data); }) }; }); </script> ``` ## Convert JSON Data to HTML ```javascript= let html = ""; json.forEach(function(val) { const keys = Object.keys(val); html += "<div class = 'cat'>"; keys.forEach(function(key) { html += "<strong>" + key + "</strong>: " + val[key] + "<br>"; }); html += "</div><br>"; }); ``` ```javascript= html += "<img src = '" + val.imageLink + "' " + "alt='" + val.altText + "'>"; ``` * `.filter()` ```javascript= json = json.filter(function(val) { return (val.id !== 1); }); <!-- remove the cat with the "id" value of 1 --> ``` * get the user's current longitude and latitude ```javascript= if (navigator.geolocation){ navigator.geolocation.getCurrentPosition(function(position) { document.getElementById('data').innerHTML="latitude: " + position.coords.latitude + "<br>longitude: " + position.coords.longitude; }); } ``` ## Reference * freecodecamp.org --- ###### tags: `Web`