# JavaScript & jQuery with AJAX( JSON ) ###### tags: `JavaScript` `AJAX` `JSON` ## JavaScript AJAX ``` // 開啟一個網路請求 let xhr = new XMLHttpRequest(); // 準備跟伺服器要取資料 xhr.open('GET', 'url', true); // 執行要資料的動作 xhr.send(); // 拿到資料後觸發下面的語法 xhr.onload = function(){ // 遠端伺服器所呈現的是 JSON 格式,要把它轉為字串才能夠使用 let data = JSON.parse(xhr.responseText); } ``` ## jQuery AJAX > 使用前要確定是否已經加載 jQuery 檔案 ``` $.ajax({ url: '', type: 'GET', dataType: 'json', success: function () { alert('資料讀取成功'); }, error: function () { alert('資料錯誤'); } }); ``` ## jQuery AJAX 直接請求從服務器加載 JSON 編碼 > [參考資料](https://api.jquery.com/jQuery.getJSON/) ``` $.getJSON( 'url', function( response ) { }); ```