ajax+json
例子: 当当网最新上架 不再先保存好资源,而是放在一个选项上就发出一个ajax请求restful架构的controller得到json数据,根据json数据动态生成html代码,显示书籍
1.restful架构的controller
@RestController
public class ApiController {
@Autowired
private BookService bookService;
@GetMapping("/book/new/{typeId}")
public List<Book> getNewlyOnlineBookWithType(@PathVariable int typeId) {
return bookService.getNewestBook(4, typeId);
}
}
2.js代码
<script type="text/javascript">
$(function() {
$.getJSON("book/new/1", function(bookArray) {
for (var i = 0; i < bookArray.length; ++i) {
var book = bookArray[i];
var dt = $("<dt>");
var img = $("<img>");
img.attr("src", "images/" + book.picture);
dt.append(img);
$("#book_history").append(dt);
var dd = $("<dd>");
var span1 = $("<span>");
span1.attr("class", "book_title")
span1.text(book.name);
dd.append(span1);
dd.append($("<br>"));
dd.append("作者: " + book.author);
$("#book_history").append(dd);
}
});
});
</script>
网友评论