数据表自定义删除列 [英] Datatable custom delete column

查看:56
本文介绍了数据表自定义删除列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有包含多个电影(行)的数据表,在每一行的末尾都有用于删除的自定义列.

I have datatable with multiple movies(rows), at the end of each row, there is custom column for delete.

这是我的数据表:

HTML

<table id="moviesTable1" class="table table-striped table-bordered">
            <thead>
                <tr>
                    <th>Title</th>
                    <th>Duration</th>
                    <th>Distributor</th>
                    <th>Origin country</th>
                    <th>Year of production</th>
                    <th></th>
                </tr>       
            </thead>
            <tbody id="moviesTbody">

            </tbody>
</table>

jquery(我也有添加电影,getAll效果很好)

jquery (I also have add movie, getAll which works fine)

var MoviesManager = {

        getAll : function() {
            $.get('MoviesServlet', function(data) {
                $('#moviesTable1').DataTable({
                    "paging": false,
                    "info": false,
                    "searching": false,
                    "columns": [
                        null,
                        null,
                        null,
                        null,
                        null,
                        {
                            "data": null,
                            render:function(data, type, row)
                            {
                                return '<button id="deleteMovie">Delete</button>'
                            },
                            "targets": -1
                        }
                    ]
                    });
                for(m in data.movies) {
                    $('#moviesTable1').dataTable().fnAddData ([
                        data.movies[m].title,
                        data.movies[m].duration,
                        data.movies[m].distributor,
                        data.movies[m].originCountry,
                        data.movies[m].yearOfProduction 
                    ]);
                }

            });
        },

        deleteMovie : function() {
            var rowSelector = $(this).closest('tr');
            var id = $('#moviesTable1').dataTable().row(rowSelector).data().id;
            params = {
                    'action': 'delete',
                    'id': id
            }
            $.post('MoviesServlet', params, function(data){
                console.log(data);
            });

        }
}

$(document).ready(function() {

    MoviesManager.getAll();

    $('#deleteMovie').click(function(e) {
        MoviesManager.deleteMovie();
    });
});


我正在尝试从选定的行(数据库中的ID)获取ID,并将其发送到Servlet.我失败了,点击没有任何反应.

I am trying to get id from selected row (id that's in database) and send it to servlet. I am failing, nothing happens on click.

这是接收ID的servlet

Here is the servlet that's receiving id

public class MoviesServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        List<Movie> movies = MovieDAO.getAll(); 

        Map<String, Object> data = new HashMap<>();
        data.put("movies", movies);

        ObjectMapper mapper = new ObjectMapper();
        String jsonData = mapper.writeValueAsString(data);

        response.setContentType("application/json");
        response.getWriter().write(jsonData);

    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String action = request.getParameter("action");

        try {
            switch(action) {
            case "add": {
                String title = request.getParameter("title");
                String duration = request.getParameter("duration");
                String distributor = request.getParameter("distributor");
                String originCountry = request.getParameter("originCountry");
                String yearOfProduction = request.getParameter("yearOfProduction");

                Movie movie = new Movie();
                movie.setTitle(title);
                movie.setDuration(duration);
                movie.setDistributor(distributor);
                movie.setOriginCountry(originCountry);
                movie.setYearOfProduction(Integer.parseInt(yearOfProduction));
                MovieDAO.addMovie(movie);
                break;
            }
            case "delete": {
                Integer id = Integer.parseInt(request.getParameter("id"));
                MovieDAO.delete(id);
                break;
            }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

}

最后是执行SQL查询的DAO

and finally DAO which executes SQL query

public static boolean delete(Integer id) {
        Connection con = ConnectionManager.getConnection();
        PreparedStatement ps = null;

        try {

            String query = "DELETE FROM movies WHERE id = ?";
            ps = con.prepareStatement(query);
            ps.setInt(1, id);

            return ps.executeUpdate() == 1;

        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            try {ps.close();} catch (Exception ex1) {ex1.printStackTrace();}
            try {con.close();} catch (Exception ex1) {ex1.printStackTrace();}
        }

        return false;
    }

推荐答案

[更新] 我正在草稿中,向每个按钮添加一个唯一的data-id属性. 您的服务器代码似乎正常!因此,在应用了这些小的更改之后,我认为一切都应该正常工作.

[UPDATED] I'm making a draft where I add a unique data-id attribute to each button. Your server' code seems ok ! So after applying those small changes, I think everything should work properly.

这是小提琴使用静态数据集

var MoviesManager = {

    getAll: function () {
        $.get('MoviesServlet', function (data) {
            $('#moviesTable1').DataTable({
                paging: false,
                info: false,
                searching: false,
                columns: [
                    null,
                    null,
                    null,
                    null,
                    null, {
            "data": null,
            render: function (data, type, row) {
                return '<button id="deleteMovie" data-id="' + data.id + '">Delete</button>'
            },
            "targets": -1
        }
                ],
                createdRow: function( row, data, dataIndex ) {
                $( row ).find('td:eq(5)').attr('data-id', data.id));
                }
            });
            for (m in data.movies) {
                $('#moviesTable1').dataTable().fnAddData([
                        data.movies[m].title,
                        data.movies[m].duration,
                        data.movies[m].distributor,
                        data.movies[m].originCountry,
                        data.movies[m].yearOfProduction
                    ]);
            }

        });
    },

    deleteMovie: function (ID) {
        params = {
            'action': 'delete',
            'id': ID
        }
        $.post('MoviesServlet', params, function (data) {
            console.log(data);
        });

    }
}

$(document).ready(function () {

    MoviesManager.getAll();
    $('body').on('click', '#deleteMovie', function(e){
        var id= $(this).attr("data-id");
        MoviesManager.deleteMovie(id);
    });
});

这是要进入jquery的数据

Here is data that gets to jquery

{"movies":[
{   "id":1,
    "title":"The Irishman",
    "duration":"03:37",
    "distributor":"Netflix",
    "originCountry":"United States",
    "yearOfProduction":2019
},
{   "id":2,
    "title":"The Lion King",
    "duration":"01:58",
    "distributor":"Walt Disney Studios",
    "originCountry":"United States",
    "yearOfProduction":2019}
]}

这篇关于数据表自定义删除列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆