美文网首页
17|Ajax和Comet

17|Ajax和Comet

作者: 井润 | 来源:发表于2020-05-18 22:37 被阅读0次

    其中在Ajax中最重要的就是XMLHttpRequest对象

    // ajax
    let xhr = new XMLHttpRequest(); // 创建xhr对象
    
    // 第一个方法:open(get | post等, "exam.php", false) 参数为请求类型,请求url,是否异步的boolean
    xhr.open("get","exam.php", false); // 调用该方法并不是真正的请求,而是请求一个请求以备发送
    
    // 发送真正的请求,接收一个参数,即作为请求主体要发送的数据,不发送数据时必须传递null,因为对于某些浏览器来说该参数是必须的
    xhr.send(null)
    
    // 检验响应的状态--->针对同步
    if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
        let data = xhr.responseText;
    }else{
        console.log(xhr.status);
    }
    
    // 异步方案
    xhr.onreadystatechange = function(){
        // xhr.readyStatus表示请求/响应过程的当前活动阶段
        // 0 未初始化,还没调用open()
        // 1 启动,已调用open()方法但未调用send()
        // 2 发送, 已调用send()方法,但未收到响应
        // 3 接收,已接收到部分响应数据
        // 4 完成,已接受到全部响应数据
        if(xhr.readyStatus == 4){
            if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
                let data = xhr.responseText;
            }else{
                console.log(xhr.status);
            }
        }
    }
    xhr.open("get","exam.php", false);
    xhr.send(null);
    
    // 在接收到响应之前还可以取消异步请求
    xhr.abort() // 在停止请求之后还应该进行解引用操作,防止内存堆积
    
    // 设置http请求头,必须放在open和send中间
    xhr.open("get","exam.php", false);
    
    xhr.setRequestHeader("accept", "application/json; charset=utf-8")
    
    xhr.send(null);
    
    // 获取响应头信息
    xhr.getResponseheader("accept");
    xhr.getAllResponseHeaders();
    
    // get请求:向现有url中添加查询字符串
    function addUrlParam(url, name, value){
        url += (url.indexOf("?") == -1 ? "?" : "&");
        url += encodeURIComponent(name) + "=" + encodeURIComponent(value);
    }
    
    // post请求:模拟表单提交
    xhr.open("get","exam.php", false);
    // 设置提交时的内容类型
    xhr.setRequestHeader("content-Type", "application/x-www-form-urlencoded")
    // 假设表单form对象已获取
    xhr.send(serialize(form));
    
    // XHR2级 -- formData --序列化表单以及创建和表单格式相同的数据(用于通过xhr传输)
    let data = new FormData();
    data.append(key,value);
    // 也就可以用表单元素的数据预先填入数据
    let data = new FormData(document.forms[0]);
    //使用FormData的好处在于不必明确地在xhr上设置请求头部
    xhr.send(new FormData(form));
    
    // 进度事件
    loadStart/progress/error/abort/load
    
    /*
    跨域资源共享CORS
    核心思想: 使用自定义的http头部让浏览器和服务器进行沟通,从而决定请求是成功还是失败
    原理:
    1.请求头指定源:Origin: http://www.baidu.com
    2.如果服务器认为这个请求可以接受,就在Access-Control-Allow-Origin头部回发相同的源信息
    Access-Control-Allow-Origin:http://www.baidu.com
    (如果是公共资源,可以回发“*”)
    3.如果没有这个头部,或者有这个头部但是源信息不匹配,浏览器就会驳回请求
    */
    
    // 主流浏览器对cros的实现方式: 在url中使用绝对路径,但有限制:不能设置自定义头部,不能发送和接收cookie,获取不到getAllResponseHeaders()的返回值
    
    // 带凭据的请求
    withCredentials属性设置为true
    // 服务器接收到带凭据的请求后,会用下面的头部来请求,如果响应不包含这个头部,浏览器将不会把响应数据交给js
    Access-Control-Allow-Credentials: true
    
    // 跨浏览器的cros
    function createCORSRequest(method,url){
        let xhr = new XMLHttpRequest();
        if("withCredentials" in xhr){
            xhr.open(method,url,true);
        }else if(typeof XDomainRequest != "undefined"){
            xhr = new XDomainRequest();
            xhr.open(method,url);
        }else{
            xhr = null;
        }
        return xhr
    }
    let req = createCORSRequest("get","http://www.baidu.com/page/");
    if(req){
        req.onload = function(){
            // 对响应数据进行处理
        };
        req.send();
    }
    /* 以上提供的公共方法有
     abort() 用于停止正在进行的请求
     onerror 用于替代onreadystatechange检验错误
     onload 用于替代onreadystatechange检验成功
     responseText 用于取得响应内容
     send() 用于发送请求
    */
    
    
    // 其他跨域技术
    1.图像ping---常用于跟踪用户点击页面和动态广告曝光数,只能get请求
        var img = new Image();
        img.onload = img.onerror = function(){
            // 操作
        }
        img.src = "http://baidu.com?name=xujaing";
    
    2.JSONP---可以直接访问响应文本,可以在浏览器和服务器之间进行双向通信,但有安全隐患
        function handleResponse(data){
            console.log(data);
        }
        var script = document.createElement("script");
        script.src = "http://a.net/json/?callback=handleResponse";
        document.body.insertBefore(script, document.body.firstChild);
    
    3.Comet (服务器推送SSE)
        常用的技术有长轮询和流
    4.Web Sockets
    

    相关文章

      网友评论

          本文标题:17|Ajax和Comet

          本文链接:https://www.haomeiwen.com/subject/istlohtx.html