后端传到前端(传一个集合,展示成表格)
controller层
@RequestMapping("/showAll")
@ApiOperation(value = "展示所有图书", httpMethod = "POST")
public void showAll(HttpServletResponse resp,String lend) throws IOException {
List<Book> bookList = userService.showAll();
System.out.println(bookList);
JSONArray books= JSONArray.fromObject(bookList);
resp.setCharacterEncoding("utf-8");
PrintWriter respWriter = resp.getWriter();
respWriter.append(books.toString());
}
JSONArray 在使用时需要在pom.xml文件中导入相关依赖
js部分
$(function () {
$.ajax({
url: 'showAll',
type: 'get',
dataType: 'json',
success: function (books) {
showData(books);
console.log(books)
},
error: function (err) {
console.log(err);
}
})
})
function showData(books) {
let str = "";
for (let i = 0; i < books.length; i++) {
str = "<tr id='books[i].id'><td>" + books[i].id + "</td><td>" + books[i].bookName +
"</td><td>" + books[i].author + "</td><td>"
+ books[i].bookType + "</td><td>" + books[i].bookNumber +
"</td><td>" + books[i].price + "</td><td>" +
"<button id='books[i].id' index="+books[i].id+" class=lend>借阅</button></td><td>" +
"<button id='books[i].id' index="+books[i].id+" class=back>归还</button></td></tr>";
$("#bookList").append(str);
}
前端 向后端传值
js部分
for(let i = 0; i < lend.length;i++) {
lend[i].addEventListener('click',function () {
let id = this.getAttribute('index')
console.log(id)
$.ajax({
type: 'post',
url: 'lend',
data:{
id:id
},
async:true,
success:function (data) {
console.log('发送id成功')
},
error:function (err) {
console.log(err)
}
})
})
}
}
controller层
@RequestMapping("/lend")
@ApiOperation(value = "借阅图书", httpMethod = "GET")
@ApiImplicitParam(name = "bookId", value = "图书编号")
public void lend(HttpServletRequest request) {
String id = request.getParameter("id");
System.out.println(id);
userService.lend(id);
}
感谢身边厉害之人的指导! 哈哈哈哈哈哈! 我希望 你的心情好一点 emo少一点 不要每天挂着一张囧字脸 让运气好一点 烦恼少一点 阳光暖暖它会照在 你身边
|