JSON Server 環境設定

圖片來源: 網路

圖片來源: 2017-05-30 (直播錄影) 進擊的前端工程師:今天就自己打造 API 吧! (高清版)

# 教學影片資源


【2019/5/3】 基本 AJAX 請求,練習 CRUD

下載 JSON server

npm install -g json-server

新增 json 檔案

隨意新增一些資料,內容自訂,並存成 .json檔案

用 json server 監控該檔案

json-server --watch db.json

HTTP 請求基本功能

index.html 內撰寫的 JavaScript 來對該資料庫進行CRUD(新增刪除修改)

程式碼

  • json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
"data-base": [
{
"id": 1,
"name": "Dylan"
},
{
"id": 2,
"name": "Gigi"
},
{
"id": 3,
"name": "Mark"
},
{
"id": 4,
"name": "Ula"
}
]
}

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<div id="create">
<input type="text" placeholder="name" class="val" />
<a href="javascript:;" class="createBtn">CREATE</a>
</div>
<div id="delete">
<input type="text" placeholder="id" class="Delval" />
<a href="javascript:;" class="delBtn">DELETE</a>
</div>
<br />
<div id="update">
<input type="text" placeholder="id" class="updateID" />
<input type="text" placeholder="new Name" class="updateName" />
<a href="javascript:;" class="updateBtn">UPDATE</a>
</div>

<ul id="users"></ul>

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
$(function () {
// 取得
$.ajax({
url: 'http://localhost:3000/data-base',
method: 'get',
dataType: 'json',
data: {},
})
.done(function (res) {
console.log(res)
const container = document.querySelector('#users')
res.forEach((item, index) => {
const children = document.createElement('li')
children.innerHTML = `${item.id} / ${item.name}`
container.appendChild(children)
})
})
.fail(function (err) {
console.log(err)
})

// 新增
const createBtn = document.querySelector('.createBtn')
createBtn.addEventListener(
'click',
function () {
const name = document.querySelector('.val').value.trim()
if (!name) return
$.ajax({
url: 'http://localhost:3000/data-base',
method: 'post',
dataType: 'json',
data: {
name: name,
},
})
},
false
)

// 刪除
const delBtn = document.querySelector('.delBtn')
delBtn.addEventListener(
'click',
function () {
const id = document.querySelector('.Delval').value.trim()
if (!id) return
$.ajax({
url: `http://localhost:3000/data-base/${id}`,
method: 'delete',
})
},
false
)

// 修改
const updateBtn = document.querySelector('.updateBtn')
updateBtn.addEventListener(
'click',
function () {
const id = document.querySelector('.updateID').value.trim()
const NewName = document.querySelector('.updateName').value.trim()
if (!id || !NewName) return
$.ajax({
url: `http://localhost:3000/data-base/${id}`,
method: 'put',
dataType: 'json',
data: {
name: NewName,
},
})
},
false
)
})