淺談Express的put與del

假設有一個景區價格列表頁,顯示當前的價目表。ajax

價目表存放在express應用的數組中:express

var tours = [
    {id:0,name:'Hood River',price:99.99},
    {id:1,name:'Oregon Coast',price:149.95}
];

價目表查看頁面,XML效果以下所示:json

<tours>
<tour price="99.99" id="0">Hood River</tour>
<tour price="149.95" id="1">Oregon Coast</tour>
</tours>

expres設置put節點用於更新價目表:api

app.put('/api/tour/:id',function (req,res) {
    var id = req.params.id;
    var p = tours.some(function (p) {
       return p.id == id;
    });
    if(p){
       if(req.query.name) tours[id].name = req.query.name;
       if(req.query.price) tours[id].price = req.query.price;
       res.json({success:true,tours:tours,p:p});
    }else{
       res.json({error:'No such tour exists.'});
    }
});

expres設置del節點用於刪除一條價目信息:數組

app.del('/api/tour/:id',function (req,res) {
    var id = req.params.id;
    var p = tours.some(function (p) {
        return p.id == id;
    });
    if(p){
        tours.splice(id,1);
        res.json({success:true,tours:tours,p:p});
    }else{
        res.json({error:'No such tour exists.'});
    }
});

使用ajax模擬發送put和del請求。app

當咱們想要更新價目信息時:url

$.ajax({
    url:"http://10.21.20.234:3000/api/tour/0?name=Woods&price=100.00",
    type:'put',
    success:function(res){
        console.log(res);
    }
});

價目表XML更新爲:spa

<tours>
<tour price="100.00" id="0">Woods</tour>
<tour price="149.95" id="1">Oregon Coast</tour>
</tours>

 

當咱們想要刪除價目信息時:code

$.ajax({
    url:"http://10.21.20.234:3000/api/tour/0",
    type:'DELETE',
    success:function(res){
        console.log(res);
    }
});

 

價目表XML更新爲:blog

<tours>
<tour price="149.95" id="1">Oregon Coast</tour>
</tours>
相關文章
相關標籤/搜索