ajax前后端互交案例

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>

展现效果

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值