Fetch请求后台的数据

     <style>
        #btn{
            width: 50px;
            height: 50px;
            background-color: red;
        }
        #output{
            width: 100px;
            height: 100px;
            background-color: pink;
        }
    </style>


 <button id="btn"></button>
 <div id="output"></div>
  //jsong格式数据
          [
            {
              "name":"张三",
              "age":25
            },
            {
              "name":"李四",
              "age":28


            }
          ]
  //js代码
    <script>
        btn.onclick=function(){
            fetch("data.json",{
                headers:{
                    "Content-Type":"application/json"
                },
            }).then(function(res){
                return res.json();
            }).then(function(data){
                console.log(data);
                var str="";
                data.forEach(item => {
                    str+=`<p>${item.name}<p>`
                   
                });
                document.getElementById("output").innerHTML=str;

            }).catch(error=>console.log(error))
               }
</script> 

/* Fetch发送请求 get*/
var page=1var pageSize=5var totalPage=0;
fetch(`/user/queryUser?page=${page}&pageSize=${pageSize}`, {

headers: {
  'Content-Type': 'application/json; charset=UTF-8'
},

}).then(res => res.json()).then(res => {
  console.log(res);
  totalPage=(Math.ceil(res.total/pageSize));
  var html = template("userTpl", res); 
  console.log(html);
  $("#userBox").html(html);
}).catch(err => {
console.log(err);
})
//Fetch请求 post
var data={
id:id,
isDelete:isDelete
}

fetch("/user/updateUser",{
headers: {
    'Content-Type': 'application/json; charset=UTF-8'
},
    method:"post",
    body:JSON.stringify(data),
}).then(res=>res.json()).then(res=>{
   console.log(res);
  if(res.success){
    location.reload();
}else{
  if(res.error){
    alert(res.message);
}
}
})
 

 

 

posted @ 2018-12-28 14:30  小金king  阅读(984)  评论(0编辑  收藏  举报