cookie的删除 封装 ajax

95 阅读1分钟

cookie的删除

cookie的删除针对于长声明周期
cookie不能直接删除,只能侧面删除
a.将key对应的value设置为""
b.将expires设置为-1 (将长生命周期过期,改为会话级别)
    let date = new Date();
    date.setDate(date.getDate()+10);
    document.cookie = "name=laowang;expires="+date;   
    document.cookie = "name='';expires=-1";

cookie的封装

增改
     function setCookie(key,value,day){
        if(day == undefined){
            document.cookie = `${key}=${value}`;
        }else{
            let date = new Date();
            date.setDate(date.getDate()+day);
            document.cookie = `${key}=${value};expires=${date}`;
        }
    }
    setCookie("age",18);
    setCookie("score",100,10);
    setCookie("score",200,5);
查
    function getCookie(key){
        let strCookie = document.cookie;
        let arrCookie = strCookie.split("; ");
​
        for(let i=0; i<arrCookie.length; i++){
            let item = arrCookie[i].split("=");
            if(item[0] == key){
                return item[1];
            }
        }
        return "";
    }
    console.log(getCookie("name"));
    console.log(getCookie("haha"));
删
    function delCookie(key){
        setCookie(key,'',-1);
    }
    delCookie("score");
    delCookie("name");

ajax的概念及作用

前提:在发送请求的操作中,页面必然要重新刷新
问题:很多页面在发请求的过程中,只有少量数据需要更新,如果完全刷新页面重新渲染,
会给用户造成不好的体验。
​
what
解决该问题的方案:ajax,异步交互的javascript和xml,是一种可以实现页面在发请求时,
无需更新整个页面,只需对局部内容更新的技术。
​
前端通过与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。传统的网页(不使用 Ajax)如果需要更新内容,必须重载整个网页页面。
​
why
为什么要使用AJAX
* 更自然、流畅的用户体验,对用户的操作即时响应
* 在不中断用户操作的情况下与Web服务器进行通信
* 更灵敏的响应用户访问,实现近似于桌面应用程序的交互效果
* 通过局部更新页面降低网络流量,提高网络的使用效率

同步和异步

同步执行方式:代码按照顺序执行,必须先执行完前一步,才能执行后一步
异步执行方式:代码在遇到消耗等待时间的代码时,会先跳过异步代码,先执行后续代码,直至异步代码消耗完等待时间后,在执行异步代码。
异步代码的分类:
    代码在执行时,有些代码只消耗执行时间,同步代码
                 还有些代码除了消耗执行时间外,还得消耗等待时间,异步代码
1.定时器
2.事件体
    xxx.onclick = function(){事件头
        事件体
    }
3.发请求接响应
    console.log(1);
    setTimeout(function(){
        console.log(2);
    },0);
    setTimeout(function(){
        console.log(3);
    },0);
    setTimeout(function(){
        console.log(4);
    },0);
    console.log(5);
结论:当同步代码和异步代码同时出现时,先执行同步,后执行异步。
只有同步遵循自上而下的执行顺序,异步谁先消耗完等待时间,谁先执行。

ajax步骤

1.掏手机   --->  创建xhr对象
    let xhr = new XMLHttpRequest();
2.拨号   ---> 调用open方法
    xhr.open("请求方式","服务器地址",是否异步true/false);
    xhr.open("get","6.server.txt",true);
3.发射  ---> 调用send
    xhr.send();
4.等待
    xhr.onreadystatechange = function(){
        //xhr.status==200,电话打通了,嘟~~~~嘟~~~~
        //xhr.readyState==4,对方接通电话
        if(xhr.status==200 && xhr.readyState==4){
5.对方说话 ---> 接收响应
    做的所有操作都是为了得到响应值
            console.log(xhr.responseText);
        }
    }

ajaxGet

get传参方式:携带在url地址中
    ip:端口+文件名?key1=value1&key2=value2...
    xhr.open("get","7.ajaxGet.php?userName="+this.value,true);
参数ajax中,echo是返回响应的关键字