前后端交互添加删除数据

164 阅读1分钟
<script>
    $(function(){
        load();
        // 前后端交互删除数据
        $(".col-xs-12").on("click",".close",function(){
            var id = $(this).attr("data-id");
            $.ajax({
                url:"http://localhost:5100/tag",
                type:"DELETE",
                data:{_id: id},
                success:function(res){
                    if(res.status === 200){
                        console.log("删除成功");
                    }
                }
            })
        })

        // 前后端交互查询显示数据
        function load() {
            $.ajax({
                url:"http://localhost:5100/tag",
                type:"GET",
                success:function(res){
                    if(res.status===200){
                        const data = res.data;
                        let html = "";    // 给html赋值一个空
                        for (let index = 0; index < data.length; index++) {
                            const element = data[index];
                            html += `<div class="alert alert-info pull-left">
                                <button type="button" data-id="${element._id}" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                                <strong>${element.text}</strong>
                            </div>`;  // 给HTML里添加数据
                        }
                        $(".col-xs-12").html(html);  // 引用HTML里的数据并显示
                    }
                    console.log(res);
                },
                error:function(err){
                    console.log(err);
                }
            })
        }
    })

</script>