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);
}
}
})
相關文章
相關標籤/搜索