小言_互联网的博客

原生ajax封装,跨域

277人阅读  评论(0)

原生JS Ajax请求
传统方法的缺点:
传统的web交互是用户触发一个http请求服务器,然后服务器收到之后,在做出响应到用户,并且返回一个新的页面,每当服务器处理客户端提交的请求时,客户都只能空闲等待,并且哪怕只是一次很小的交互、只需从服务器端得到很简单的一个数据,都要返回一个完整的HTML页,而用户每次都要浪费时间和带宽去重新读取整个页面。这个做法浪费了许多带宽,由于每次应用的交互都需要向服务器发送请求,应用的响应时间就依赖于服务器的响应时间。这导致了用户界面的响应比本地应用慢得多。
什么是ajax?
ajax的出现,刚好解决了传统方法的缺陷。AJAX 是一种用于创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现

AJAX:异步更新

这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

  • js原生的ajax 主要是做前后端分离项目 请求API (程序应用级 接口)
    *
    * 调用的结果 —后台数据返回
    * 写法 跨域原理(为什么会有跨域) cros jsonp
    *
    * 异步请求 局部刷新技术
    * —朋友圈评论 点赞
    *
    *
    * 对象 XMLHttpRequest
    * 状态码 200 成功 404 丢失 500服务器
    * 提供了API:open 建立服务器之间的链接 参数1:请求的方式 get post 参数2:api路径 参数3:async true/false 用户名和密码
    * send() 向服务器发送请求
XMLHttpRequest 对象
XMLHttpRequest对象是ajax的基础,XMLHttpRequest 用于在后台与服务器交换数据。
这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
目前所有浏览器都支持XMLHttpRequest.
abort()	停止当前请求 
getAllResponseHeaders()	把HTTP请求的所有响应首部作为键/值对返回
getResponseHeader("header")	返回指定首部的串值
open("method","URL",[asyncFlag],["userName"],["password"]) 	
建立对服务器的调用。method参数可以是GET、POST或PUT。
url参数可以是相对URL或绝对URL。
这个方法还包括3个可选的参数,是否异步,用户名,密码
send(content)	向服务器发送请求
setRequestHeader("header", "value")	把指定首部设置为所提供的值。
在设置任何首部之前必须先调用open()。
设置header并和请求一起发送 ('post'方法一定要 )

AJAX五步使用法:

1.创建XMLHTTPRequest对象
2.使用open方法设置和服务器的交互信息
3.设置发送的数据,开始和服务器端交互
4.注册事件
5.更新界面

 //1.建立ajax对象
    var http=new XMLHttpRequest();
    //2.建立服务器链接
    http.open("get","");//第三个参数不写默认异步请求
    //3.发送请求
    http.send();
    //4.建立ajax事件
    http.onreadystatechange=function (){
        //readyState  4 请求读取完成
        //status  响应的状态码  200  500
        if(http.readyState==4&&http.status==200)
        {
            //5.渲染界面http.responseText  http.response    json
            //http.responseText
        }
    }

AJAX 封装

进方法里面,要用的时候,直接调用就好了

/*
     * 封装ajax
     * get   "www.baidu.com/api?id=1&name=2"
     *
     * async  true  异步(请求和后续代码同时执行)   false  同步(等待请求完成在执行)
     * */
    function method(med, api, async, data, callback) {
        var http = new XMLHttpRequest();
        if (med == "get") {
            if (data) {
                api += "?";
                api += data;
            }
            http.open(med, api, async);
            http.send();
        }
        else {
            http.open(med, api, async);
            if (data) {
                http.send(data);
            }
            else {
                http.send();
            }
        }
        http.onreadystatechange = function () {
            if (http.readyState == 4 && http.status == 200) {
                callback(http.response);
            }
        }
    }
    //192.168.90.1/sue/php/read.php   读数据
    //192.168.90.1/sue/php/userLogin.php  用户登录   111  112
    method("get", "http://www.maodou.com/sue/php/userLogin.php", true, "userid=111&userpwd=112", function (result) {
        if (JSON.parse(result)[0].count == 1) {
            alert("登录成功!")
        }
    });

JS几种跨域方法和原理

(协议不同 端口不同 主机名称)-------产生跨域。
js跨域是指通过js在不同的域之间进行数据传输或通信

1.通过jsonp跨域
在js中,我们直接用XMLHttpRequest请求不同域上的数据时,是不可以的。但是,在页面上引入不同域上的js脚本文件却是可以的,jsonp正是利用这个特性来实现的。即:是通过src + callback回调函数来请求。

2.cros跨域
在php文件里面配 header('Access-Control-Allow-Origin: * ');

<script>
    /*
     * 解决跨域
     * (跨域资源共享)
     *
     * 报错  报  Access-Control-Allow-Origin   出现跨域访问
     * cros  jsonp
     *  cros 在后端配置cros跨域请求
     * https://www.baidu.com/img/jijiandong_fe814ef3a7b6710df2ee25b9d0181cef.gif
     *
     *jsonp  跨域原理是通过src +  callback回调函数来请求 ---不是ajax
     *
     *
     * */

    function method(med, api, async, data, callback) {
        var http = new XMLHttpRequest();
        if (med == "get") {
            if (data) {
                api += "?";
                api += data;
            }
            http.open(med, api, async);
            /*http.setRequestHeader("header","Access-Control-Allow-Origin:*");
            http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");*/
            http.send();
        }
        else {
            http.open(med, api, async);
            if (data) {
                http.send(data);
            }
            else {
                http.send();
            }
        }

        http.onreadystatechange = function () {
            if (http.readyState == 4 && http.status == 200) {
                callback(http.response);
            }
        }
    }
    //  cros  在php文件里面配 header('Access-Control-Allow-Origin: * ');
    /*var src = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=1&cb=getData";
    method("get", src, true, "", function (result) {
        console.log(result);
    })*/
</script>
<script>
    function getData(res){
        console.log(res);
    }
</script>
<script src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=1&cb=getData" type="text/javascript"></script>

数据节流

<input type="text" id="txt"/>
<script>
    /*
     * 用户输入的节流
     * */
    function method(med, api, async, data, callback) {
        var http = new XMLHttpRequest();
        if (med == "get") {
            if (data) {
                api += "?";
                api += data;
            }
            http.open(med, api, async);
            http.send();
        }
        else {
            http.open(med, api, async);
            if (data) {
                http.send(data);
            }
            else {
                http.send();
            }
        }
        http.onreadystatechange = function () {
            if (http.readyState == 4 && http.status == 200) {
                callback(http.response);
            }
        }
    }
    function getData(time,t){
        return function (){
            //清除计时器
            clearTimeout(time);
            time=setTimeout(function (){
                method("post","./data.txt",true,"",function (result){
                    console.log(result);
                });
            },t);
        }
    }
    var txt = document.getElementById("txt");
    var time;
    txt.addEventListener("keyup",getData(time,500));
</script>

example:

百度智能搜索

    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .block {
            width: 600px;
            height: 35px;
            border: 1px solid #000;
            margin: auto;
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            bottom: 0;
            font-size: 0;
        }

        .block > input {
            position: absolute;
            left: 0;
            top: 0;
            border-style: none;
            outline: none;
            box-sizing: border-box;
            width: 500px;
            height: 35px;
            font-size: 1rem;
            padding-left: 0.5rem;
        }

        .block > span {
            position: absolute;
            right: 0;
            font-size: 1rem;
            display: inline-block;
            width: 100px;
            height: 35px;
            color: #fff;
            background: #15a0ff;
            text-align: center;
            line-height: 35px;
        }

        .nav {
            font-size: 0.9rem;
            list-style: none;
            position: absolute;
            top: 35px;
            left: -1px;
            width: 500px;
            border: 1px solid #979797;
        }

        .nav > li {
            padding-left: 0.5rem;
            line-height: 30px;
        }

        .nav > li:hover {
            background: #e4e4e4;
        }

        .nav a {
            color: #000;
            font-weight: bold;
            text-decoration: none;
        }

        .bgcolor {
            background: #e4e4e4;
        }
    </style>
</head>
<body>
<div class="block">
    <input id="ipt" type="text"/>
    <span id="btn">百度一下</span>
    <ul class="nav">
    </ul>
</div>
<script>
    /*
     * https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=
     * https://www.baidu.com/s?wd=
     *
     * */
    var script = null;
    var isshu = false;
    var index = 0;
    var ipt = document.getElementById("ipt");
    var btn = document.getElementById("btn");
    var nav = document.getElementsByClassName("nav")[0];
    var api = " https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su";
    ipt.addEventListener("keyup", getInput(api));



    ipt.addEventListener("keydown", function (e) {
        if (e.keyCode == 38 || e.keyCode == 40) {
            e.preventDefault();//处理事件默认行为
        }
    })
    btn.addEventListener("click", function () {
        location.href = "https://www.baidu.com/s?wd=" + ipt.value;
    })
    document.body.addEventListener("keyup", function (e) {
        if (!nav.children.length)return;
        if (e.keyCode == 38) {
            isshu = true;
            index--;
            if (index < 0) {
                index = nav.children.length - 1;
            }
            nav.children[index + 1 > nav.children.length - 1 ? 0 : index + 1].className = "";
            nav.children[index].className = "bgcolor";
            ipt.value = nav.children[index].innerText;
        }
        else if (e.keyCode == 40) {
            isshu = true;
            if (document.getElementsByClassName("bgcolor").length) {
                index++;
            }
            if (index > nav.children.length - 1) {
                index = 0;
            }
            nav.children[index - 1 < 0 ? nav.children.length - 1 : index - 1].className = "";
            nav.children[index].className = "bgcolor";
            ipt.value = nav.children[index].innerText;
        }
    });




    function getInput(src) {
        var t;
        return function () {
            isshu = false;
            var that = this,
                    args = arguments;
            clearTimeout(t);
            t = setTimeout(function () {
                //jsonp ipt.value
                jsonp.apply(that, [args, src])
            }, 500);
        }
    }

    //封装一个jsonp方法
    function jsonp() {
        if (isshu) {
            return;
        }
        //动态创建
        if (script) {
            script.remove();
        }
        script = document.createElement("script");
        script.src = arguments[1] + "?" + "wd=" + this.value + "&cb=getData";
        document.body.appendChild(script);
    }
    //回调函数
    function getData(res) {
        nav.innerHTML = "";
        res.s.forEach(function (val, index) {
            var lilist = document.createElement("li");
            lilist.innerHTML = "<a href='https://www.baidu.com/s?wd=" + val + "'>" + val + "</a>";
            nav.appendChild(lilist);
        });
        index = 0;
    }
</script>

转载:https://blog.csdn.net/weixin_44892520/article/details/100829458
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场