One: source code acquisition
This article is a use case based on jQuery-encapsulated ajax acquisition and submission request. It uses the public test interface and can be used directly to use the study contact. The source code of the case is as follows. Students who do not have members can privately chat with me "Book List Acquisition"
Two: the effect of the case
The basic function of this case is to click the add button according to the book title, author name, publisher information, etc. input by the user, and then add it to the book list below, and click the delete button to delete the corresponding data. Basic functions of the case
Three: source code analysis
The basic realization of the operation of adding, deleting, modifying and checking data in this section
3.1 Data rendering
Here, the data acquisition and rendering are encapsulated into a function, because subsequent delete, add and other operations need to re-render the data, we obtain the data and send a request with the type of $.ajax as GET. The specific operation is based on the interface document. To achieve the requirements, the obtained book data is res.data, and the $.each method encapsulated by jQuery traverses the data and adds each item to a new array. Then convert it to a string and add it to the tbody of the page table.
var getdata=()=>{
$.ajax({
type:'GET',
url:'http://www.liulongbin.top:3006/api/getbooks',
data:{},
success:(res)=>{
console.log(res);
if(res.status!=200){
return alert('数据获取失败')
}
var rowsarr=[]
$.each(res.data,(index,item)=>{
rowsarr.push('<tr><td>'+item.bookname+'</td><td>'+item.author+'</td><td>'+item.publisher+'</td><td><a href="javascript:;" class="del" dataid="'+ item.id +'">删除</a></td></tr>')
})
var rowsStr=rowsarr.join(' ');
console.log(rowsStr);
$('tbody').html(rowsStr)
}
})
}
3.2 Data deletion
The deletion of data needs to use the custom attribute added when the data is added. The value of this attribute is the id value of no book data. The data needed to delete is to provide an id data. After deletion, re-render and call once to get the data.
$('tbody').on('click','.del',function(){
var id=$(this).attr('dataid')
// console.log(id);
$.ajax({
type:'GET',
url:'http://www.liulongbin.top:3006/api/delbook',
data:{
id:id
},
success:(res)=>{
if(res.status!=200){
return alert('数据删除失败')
}
getdata()
}
})
})
3.3 Data addition
$('.add-btn').on('click',function(){
var name_val=$('.name-ipt').val()
var author_val=$('.author-ipt').val()
var publisher_val=$('.publisher-ipt').val()
if(name_val.trim().length<=0||author_val.trim().length<=0||publisher_val.trim().length<=0){
return alert('请填写完整信息');
}else{
$.ajax({
type:'POST',
url:'http://www.liulongbin.top:3006/api/addbook',
data:{
bookname:name_val,
author:author_val,
publisher:publisher_val
},
success:(res)=>{
if(res.status!=201){
return alert('数据添加失败')
}
getdata()
$('.name-ipt').val('')
$('.author-ipt').val('')
$('.publisher-ipt').val('')
}
})
}
})