ajax+json
例子: 當(dāng)當(dāng)網(wǎng)最新上架 不再先保存好資源糯耍,而是放在一個(gè)選項(xiàng)上就發(fā)出一個(gè)ajax請求restful架構(gòu)的controller得到j(luò)son數(shù)據(jù)藏斩,根據(jù)json數(shù)據(jù)動態(tài)生成html代碼据忘,顯示書籍
1.restful架構(gòu)的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>