# restful api 串接 2
###### tags: `restful api`
呈上一個[章節](https://hackmd.io/ZmPzd6lMTTqsAR6ZArNq3Q?both)
1.輸入json-server --watch ./deta/deta.json
跑出這個畫面

2.點開httpL//localhost:3000得到以下畫面

3.在`/user`下面應該還要有一個`db`的link ,但是因為JSON-SERVER原始檔問題渲染出錯,網路上找了很多方法都還是無法解開問題.不過在網址上輸入`http://localhost:3000/users`是可以撈到資料的,應該是無礙接下來實做.
而user和db的差異在於
user只會讓你看到部分物件資料,db會讓你看到整包資料

4.輸入`http://localhost:3000/users/1` 會得到第一筆資料

### POSTMAN
1.安裝chcorm api開發/串接工具 postman,適合作為測試用(不適合正是專案使用,讀取效率較慢)

點開畫面是,可以先點 **take me straight to the app,I will create an account another time.**

2.點入後進入以下畫面
a.開啟新的tab,多個專案
b.選取行為GET、POST、PUT...
C.貼入URL,這裡可以使用剛剛JSON-SERVER http://localhost:3000/users
d.送出後e會跑出資料

### POSTMAN POST 新增資料
直接在postman裡面新增資料,點選**GET**,並點**body**,選擇**raw**,接著選**JSON格式**,在畫面輸入要新增資料.接著點選SEND按鈕
{
"name": "linda"
}

12.回到VSCODE deta.json檔會看到剛剛新增資料自動輸入到裡面

13.回到http://localhost:3000/users 按**F5**重整會得到新的資料

### POSTMAN PUT修改資料
因為`http://localhost:3000/users`是整包資料,修改資料是針對一筆資料做修改,假設要對第3筆資料做修改打成`http://localhost:3000/users/3`
把名字改成**Samdy**,本來是**Ann**,send出後可以發現,vs code檔案和`http://localhost:3000/users`都跟著修改

### jQuery Ajax
[jQuery Ajax官方資料](https://api.jquery.com/jquery.ajax/)
[jQuery Ajax w3cshool資料](https://www.w3schools.com/jquery/jquery_ref_ajax.asp)
1.基本資料,**method**預設是**get**,如果沒有打就會是get
```
$(function){
$.ajax({
url:'',
method:'',
dataType:'',
data:,
})
}
```
2.加入cosole.log測試
```
$(function(){
$.ajax({
url:'http://localhost:3000/users',
method:'get',
dataType:'json',
data:{ }
}).done(function(res){
console.log(res)
}).fail(function(err){
console.log(err)
})
})
```
<kbd>done(function(res)</kbd>請求成功完成後呼叫回撥。<kbd>fail(function(err)</kbd>請求失敗。
網路資料-[ajax成功失敗事件處理 - jQuery AJAX success and error](http://www.pureexample.com/tw/jquery/ajax-success-and-error.html)
網路資料-[jQuery ajax() 成功錯誤 VS .done() 。fail()](http://www.tastones.com/zh-tw/stackoverflow/jquery/jquery-deferred-objects-and-promises/jquery_ajax_success_error__vs__.done_.fail/)
3.開google console除錯前,先看cs code有沒有安裝**live server**,
有的話點右下角,會跳出新畫面,我這邊是`http://127.0.0.1:5555/`
用這個畫面去看.

4.試著在畫面渲染資料分別html和js代碼是
`<ul id="users"></ul>`
```
$(function(){
$.ajax({
url:'http://localhost:3000/users',
method:'get',
dataType:'json',
data:{ }
}).done(function(res){
console.log(res)
$('#users').empty()
res.forEach(function(user){
$('#users').append('<li>'+ user.name)
})
}).fail(function(err){
console.log(err)
})
})
```
<kbd>[empty()](https://api.jquery.com/empty/)</kbd>
This method removes not only child (and other descendant) elements, but also any text within the set of matched elements. This is because, according to the DOM specification, any string of text within an element is considered a child node of that element. 此方法不僅刪除子(和其他後代)元素,而且刪除匹配元素集中的所有文本。這是因為根據DOM規範,元素內的任何文本字符串都被視為該元素的子節點。
<kbd>forEach</kbd>陣列
得到畫面結果如下

### jQuery Ajax input type add name 在畫面新增item
**註:在畫面input type新增名字,畫面更新是因為live server不是因為程式,如果不是使用live server就不會自動更新.**
html: 在使用者沒有打任何字但還是按input發送情況下也是會送出表單,並造成**空資料空陣列**問題,所以必須先驗證,jQuery有驗證表單plugin可參考,也可以自己寫.
[jQuery validate EN](https://jqueryvalidation.org/)
[jQuery validate CN](https://www.runoob.com/jquery/jquery-plugin-validate.html)
```
<div id="create">
<input type="text" placeholder="name">
<a href="jacaScript:;" >Create</a>
</div>
```
JS: onclick 觸發 ajax put新增function , 以下範例因為沒有寫防止沒有內容情況下輸入,所以會出現空陣列
```
$('#create > a').on('click',function(){
$.ajax({
url:'http://localhost:3000/users',
method:'post',
dataType:'json',
data:{
name:$('#create > input').val()
}
})
})
```

寫入防止空白輸入語法<kbd>trim()</kbd>,去頭去尾還是空值<kbd>!name</kbd>送出失敗<kbd>return false</kbd>
```
$('#create > a').on('click', function () {
let name = $('#create > input').val().trim();
if(!name) return false;
$.ajax({
url: 'http://localhost:3000/users',
method: 'post',
dataType: 'json',
data: {
name: $('#create > input').val()
}
})
})
```
### jQuery Ajax delete 刪除
1.把creat input type複製另一個input type ,id和name改delete.
```
<div id="delete" >
<input type="text" placeholder="name">
<a href="javascript:;">Delete</a>
</div>
```
2.因為要使用在輸入框輸入user id方式來刪除,需要在畫面打印出id編號,回到
`res.forEach(function (user) { }`去新增 <kbd>user.id</kbd>
刪除function可以copy post來修改,將id 和 name都改成delete , 注意url因為是使用id指定 所以是 `url: 'http://localhost:3000/users/' + id ,`
$('#delete > a').on('click', function () {
let id = $('#delete > input').val().trim();
if(!id) return false;
$.ajax({
url: 'http://localhost:3000/users/' + id ,
method: 'delete',
dataType: 'json',
})
.done(function (res) {
console.log(res)
})
.fail(function (err) {
console.log(err)
})
})
### jQuery Ajax update 修改
1.修改比較複雜 , input type需要兩個 ,先指定id ,抓到id之後輸入修改資料,
並為了做區隔,分別給<kbd>name="id"</kbd>和<kbd>name="name"</kbd>
```
<div id="update" >
<input type="text" placeholder="id" name="id">
<input type="text" placeholder="name" name="name">
<a href="javascript:;">Update</a>
</div>
```
```
$('#update > a').on('click', function () {
let id = $('#update > input[name=id]').val().trim();
if(!id) return false;
let name = $('#update > input[name=name]').val().trim();
if(!name) return false;
$.ajax({
url: 'http://localhost:3000/users/' + id ,
method: 'put',
dataType: 'json',
data: {
name:name
}
})
})
```
