backend
package cn.lnfvc.controller;
import cn.lnfvc.pojo.Book;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@CrossOrigin
public class BookController {
private int max=9;
List<Book> books=new ArrayList<>();
public BookController() {
for (int i = 0; i <=max ; i++) {
Book book=new Book();
book.setId(i);
book.setName("mybook"+i);
book.setPrice(i*10);
books.add(book);
}
}
@GetMapping("/books")
public List<Book> findAllBooks(){
return books;
}
@GetMapping("/books/{id}")
public Book loadBook(@PathVariable("id") int id){
Book book=null;
for (int i=0;i<max;i++){
if(books.get(i).getId()==id){
book=books.get(i);
break;
}
}
return book;
}
@PostMapping("/books")
public Book addBook(@RequestBody Book book){
book.setId(++max);
books.add(book);
return book;
}
}
FrontEnd
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button>test</button>
<script>
document.querySelector('button').addEventListener('click',function(){
let xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
alert(xhr.responseText)
}
}
}
xhr.open('POST','http://localhost:9000/books')
xhr.setRequestHeader('Content-Type','application/json')
let book={name:'harry polter',price:23.45}
xhr.send(JSON.stringify(book))
})
</script>
</body>
</html>
网友评论