ajax 案例

97 阅读1分钟

请先登录,再获得数据

获取用户数据

pagenum=1 表示取第一页的数据 / / pagesize=5 表示显示5条数据 */ let url = 'timemeetyou.com:8889/api/private…'; xhr.open('get', url, true); xhr.setRequestHeader('Authorization',localStorage.token) xhr.send(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { let res = JSON.parse(xhr.responseText) console.log(res); } } }

    function login() {
        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 res = JSON.parse(xhr.responseText)
                console.log(res);
                localStorage.token = res.data.token;
                // location.href="shop.html"
            }
        }
    }

</script>


作者:上单掘墓
链接:juejin.cn/post/705150… 来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。