ajax操作真实接口

121 阅读1分钟
<button onclick="fn1()">先登录再获取</button><br>    
<button onclick="fn2()">获取</button>   
 <script>        
function fn2(){            
//先判断是否有token 有就不提示,没有提示请先登录再获取            
if(!localStorage.token){                
alert('请先登录再获取');               
 return;            }            
let xhr = new XMLHttpRequest();            
//pagenum=1表示第一页的数据            
//pagesize=3表示显示3条数据            
let url = 'http://timemeetyou.com:8889/api/private/v1/users?pagenum=1&pagesize=3';
xhr.open('get',url,true);            
xhr.setRequestHeader('Authorization',localStorage.token);            
xhr.send();            
xhr.onreadystatechange = function(){                
if(xhr.readyState == 4){                    
let obj = JSON.parse(xhr.responseText);                    
console.log(obj);                }            }        }        
function fn1(){        
let xhr = new XMLHttpRequest();        
let url = 'http://timemeetyou.com:8889/api/private/v1/login';       
 xhr.open('post',url,true);       
 let params = {            
username:"admin",            
password:'123456'        }        
/* post需要添加请求头 */        
/* 请求回来的内容是json格式 */       
 /* Content-type 表示请求内容的类型 */        
/* application/json 表示请求内容的类型的具体的值 */        
xhr.setRequestHeader("Content-type","application/json");        
xhr.send(JSON.stringify(params));        
xhr.onreadystatechange = function(){            
if(xhr.readyState == 4){            
let obj = JSON.parse(xhr.responseText);            
console.log(obj);            
localStorage.token = obj.data.token;            
//location.href = "./demo/shop.html";            }        }        }    
</script>