数据的添加和删除

114 阅读1分钟

在请求数据的时候不仅有显示内容,还有添加和删除内容 1.添加:

     // 添加
    $(function () {
        load();
        $("form").submit(function () {
            $.ajax({
                url: "http://localhost:3001/tag",
                type: "POST",
                data: { text: $("#text").val() },
                success: function (res) {
                    if (res.status === 200) {
                        load();
                        console.log("添加成功");
                    }
                }
            })
            return false;
        })

2.删除:

//删除 (".close").on("click", ".close", function () { var id = (this).attr("data-id"); $.ajax({ url: "http://localhost:3001/tag", type: "DEFLETE", data: { _id: id }, success: function (res) { if (res.status === 200) { console.log("删除成功"); } } }) })

//数据 function load() {//用function load()来封装$.ajax可以直接显示数据

            $.ajax({
                url: " http://localhost:3001/tag",
                type: "GET",
                success: function (res) {
                    if (res.status === 200) {
                        const data = res.data;
                        let 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>`;
                        }
                        // 显示
                        $(".col-xs-12").html(html);


                    }
                    console.log(res);
                },
                error: function (err) {
                    console.log(err);
                }
            })
        }
    })
    
    

33.png