Skip to main content

Ajax 範例 1

本範例使用 Jquery 的 ajax 所以請記得載入。

測試 API 來源: https://swapi.dev/

使用 get 取得 https://swapi.dev/api/starships/ 的資料

ajax 得到的 json 轉 表格。

換日期才觸發。

使用 $.each() 遍歷每個資料。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"
></script>
<title>Document</title>
</head>
<body>
<table class="mytable" id="list_table_json">
<thead>
<input id="myday" type="date" />
<tr>
<th>Name</th>
<th>Manufacturer</th>
</tr>
</thead>
</table>
<script>
$(document).ready(function () {
$('#myday').change(function () {
var date = $(this).val();
console.log(date, 'change');
$.ajax({
url: 'https://swapi.dev/api/starships/',
dataType: 'json',
type: 'get',
cache: false,
success: function (data) {
/*console.log(data);*/
var event_data = '';
$.each(data.results, function (index, value) {
/*console.log(value);*/
event_data += '<tr>';
event_data += '<td>' + value.name + '</td>';
event_data += '<td>' + value.manufacturer + '</td>';
event_data += '</tr>';
});
$('#list_table_json').append(event_data);
},
error: function (d) {
/*console.log("error");*/
alert('404. Please wait until the File is Loaded.');
},
});
});
});
</script>
</body>
</html>