注意:本项目基于 jQuery 文件下进行的 Ajax 请求项目,需要映入jQuery文件!
< body style =" padding : 15px; " > < div class = " panel panel-primary" > < div class = " panel-heading" > < h3 class = " panel-title" > 添加新图书</ h3> </ div> < div class = " panel-body form-inline" > < div class = " input-group" > < div class = " input-group-addon" > 书名</ div> < input type = " text" class = " form-control" id = " iptBookname" placeholder = " 请输入书名" > </ div> < div class = " input-group" > < div class = " input-group-addon" > 作者</ div> < input type = " text" class = " form-control" id = " iptAuthor" placeholder = " 请输入作者" > </ div> < div class = " input-group" > < div class = " input-group-addon" > 出版社</ div> < input type = " text" class = " form-control" id = " iptPublisher" placeholder = " 请输入出版社" > </ div> < button id = " btnAdd" class = " btn btn-primary" > 添加</ button> </ div> </ div> < table class = " table table-bordered table-hover" > < thead> < tr> < th> Id</ th> < th> 书名</ th> < th> 作者</ th> < th> 出版社</ th> < th> 操作</ th> </ tr> </ thead> < tbody id = " tb" > </ tbody>
//自己去相关的官网下载 bootstrap.css文件 和 jQuery 文件 引入<link rel="stylesheet" href="./lib/bootstrap.css" /><script src="./lib/jquery.js" ></script>
< script> getBooks ( ) ; function getBooks ( ) { $. ajax ( { type: 'GET' , url: 'http://www.liulongbin.top:3006/api/getbooks' , success: function ( res) { if ( res. status === 200 ) { let str = '' ; res. data. forEach ( item => { str += `<tr><td> ${ item. id} </td><td> ${ item. bookname} </td><td> ${ item. author} </td><td> ${ item. publisher} </td><td><a data-id=" ${ item. id} " class="delete" href="javascript:;">删除</a> </td></tr>` ; } ) ; $ ( '#tb' ) . html ( str) ; } } } ) } $ ( 'body' ) . on ( 'click' , '.delete' , function ( ) { if ( ! confirm ( '你确定要删除吗?你好狠!' ) ) { return ; } let id = $ ( this ) . attr ( 'data-id' ) ; $. ajax ( { type: 'GET' , url: 'http://www.liulongbin.top:3006/api/delbook' , data: { id: id} , success : function ( res) { alert ( res. msg) ; if ( res. status === 200 ) { getBooks ( ) ; } } } ) } ) ; $ ( '#btnAdd' ) . on ( 'click' , function ( ) { let bookname = $ ( '#iptBookname' ) . val ( ) . trim ( ) ; let author = $ ( '#iptAuthor' ) . val ( ) . trim ( ) ; let publisher = $ ( '#iptPublisher' ) . val ( ) . trim ( ) ; if ( bookname == '' || author == '' || publisher == '' ) { alert ( '参数不能为空' ) ; return ; } $. ajax ( { type: 'POSt' , url: 'http://www.liulongbin.top:3006/api/addbook' , data: { bookname: bookname, author: author, publisher: publisher } , success : function ( res) { alert ( res. msg) ; if ( res. status === 201 ) { getBooks ( ) ; } } } ) ; } ) ; < / script>
实现效果: