Ajax封装
function queryStringify(obj){
let str = ''
for(let k in obj) str += `${k}=${obj[k]}&`
return str.slice(0,-1)
}
function ajax(options){
let defaultoptions={
url:"",
method:"GET",
async:true,
data:{},
headers:{
"content-type":"application/x-www-form-urlencoded"
},
success:function (){},
error:function (){}
}
let{url, method, async, data, headers, success, error}={
...defaultoptions,
...options
}
if(typeof data ==='object'&& headers["content-type"]?.indexOf("json")>-1){
data = JSON.stringify(data)
}else {
data = queryStringify(data)
}
if(typeof data==='object'&&data)url += '?'+data
const xhr = new XMLHttpRequest()
xhr.open(method,url,async)
xhr.onload=function (){
if(!/^2\d{2}$/.test(xhr.status)){
error('错误状态码:${xhr,status}')
return
}
try {
let result = JSON.parse(xhr.responseText)
success(result)
}catch (err){
error('解析失败!因为后端返回结果不是JSON格式字符串')
}
}
for (let k in headers) xhr.setRequestHeader(k,headers[k])
if(/^get$/i.test(method)){
xhr.send()
}else {
xhr.send(data)
}
}
export default ajax
前后端互交
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" name="" id="mytext">
<button id="myadd">add</button>
<ul class="list"></ul>
<script type="module">
import ajax from "./util.js"
// console.log(ajax)
class Todlist{
constructor(select) {
this.listEle= document.querySelector(select)
this.listdata=[]//列表数据
this.init()
}
init(){
//初始化
//获取数据
this.getlist()
this.bindEvent()
}
bindEvent(){
this.listEle.onclick = (evt)=>{
// console.log(evt.target)
if(evt.target.nodeName==="BUTTON"){
this.removeItem(evt.target)
}
}
}
getlist(){
//获取数据
ajax({
url:"http://localhost:3000/list",
success: (res)=>{
// console.log(res)
this.listdata=res;
this.render()
},
error:function (){
}
})
}
render(){
//console.log("render")
this.listEle.innerHTML=this.listdata.map(item=>`
<li>
${item.text}
<button data-index=${item.id}>del</button>
</li>
`).join("")
}
addItem(text){
// console.log(text)
//先在数据库添加后,成功回调里,页面添加
ajax({
url:`http://localhost:3000/list`,
method:"POST",
data:{
text
},
success: (res)=>{
// console.log("成功",res)
// location.reload()//全局刷新页面
this.listdata= [...this.listdata,res]
this.render()
},
error:function (){
}
})
}
removeItem(target){
target.parentNode.remove()//删除页面
// console.log(target.dataset.index)
ajax({
url:`http://localhost:3000/list/${target.dataset.index}`,
method:"DELETE",
success: (res)=>{
console.log("删除成功")
},
error:function (){
}
})
}
updataItem(){
}
}
var obj=new Todlist(".list")
// console.log(obj)
myadd.onclick= function (){
// console.log(mytext.value)
obj.addItem(mytext.value)
}
</script>
</body>
</html>
展现效果