014 Javascript(148

[A] JSONP跨域

                测试工具:在线JSONP接口测试

            1. 跨域拦截

                   1. 我们通过一个.html文件区请求另一个.php或者.txt文件的内容的时候 必须保证该请求的.html文件和被请求的.php和.txt文件在同一个协议和IP下,才能请求成功。

                    如请求文件:http://localhost/PHP/22json跨域语法.html

                    被请求文件:localhost/PHP/data.txt


                   2. 请求文件.html与被请求文件.php/.txt不在同一个协议和IP下,请求会被拦截,导致请求失败

                    如请求文件:http://localhost/PHP/22json跨域语法.html

                    被请求文件:"https://api.asilu.com/weather/"

                      报错内容:Access to XMLHttpRequest at '.php/.txt' from origin 'http://localhost' has been blocked by CORS policy:   No 'Access-Control-Allow-Origin' header is present              on the requested resource.

                      即同源策略禁止读取位于'.php/.txt'的远程资源,因为核中缺少'Access-Control-Allow-Origin'请求头


                  【注】ajax只能去下载同源的数据,跨源数据禁止下载


            2. 同源策略:
                  1. 同协议
                  2. 同域名/IP
                  3. 同端口号

           3.  跨源需求:

                  你在做本地开发的时候,你的文件夹下的文件不是在一个域下面的,当你一个文件需要发送ajax请求,

                  请求另外一个页面的内容的时候,就会跨域。不是为什么要跨域,而是你如果不搭服务器,

                  又想要ajax请求的话是不得不跨越。跨域的作用就是让你能访问不是同一个域的文件。


            4. 跨源的方式:

      1. 修改ajax的同源协议(不建议,因为不安全)

      2. 间接跨源,即用html页面委托php页面进行跨源的方式

      【这是因为】我们当前的html页面是不可以跨源的,但是我们的php页面是可以跨源的

      3. JSONP跨域

[B] JSONP跨域

    1. JSONP跨域原理:

                  1. src的属性是可是实现跨源的,如<img src="" alt="">,如script src="">等都包含src属性。

                  2. 故可将跨域内容写在.js文件中,然后在当前.html页面调用该.js文件

                      【实现原理】在当前.html中预先定义函数fun,再在跨域的.js中调用该函数,并将需要跨域的语句作为参数调用;

                                      最后,在.html文件中调用该.js文件即可实现跨源

                      【实现过程】1. 在.html文件中先定义函数download();

                                    2. 在.js文件中写入:download("I am a string");

                                        相当于在script中调用了语句download("I am a string");即调用了函数download();



             2. 两大问题:

                  1. 在需要的时候才加载数据

                  2. 能否因为除.js以外的其他路径       

                
             3. 动态加载数据解决问题2.1:
                    即在事件函数中引入script标签,并添加其属性和内容
                window.onload = function(){
                    var oBtn = document.getElementById("btn1");
                    oBtn.onclick = function(){
                        var oScript = document.createElement("script");
                        oScript.src = "demo.js";
                        document.head.appendChild(oScript);
                    }
                }

            4. 【注】对于计算机而言,文件后缀没有任何作用

                  文件后缀作用:用于给计算机中的中间快速识别该用哪个软件打开这个文件

                  在该案例中,只要所需导入的文件的后缀与文件的真实后缀相同即可成功调用。

            

            5. JSONP跨域的使用流程(作者定义):

                  1. 先声明一个函数,这个函数有一个形参;

                  2. 在需要下载数据的地方,动态添加script标签,将标签的src属性设置成被下载数据文件的连接;

                  3. 当script插入到页面上的时候,就会调用已经封装好的函数,将我们所需要的数据传过来。

[C] 练习

  1. 天气查询

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <style>
        .box{  1200px; border: solid black 1px}
        .rowin{ border: solid red 1px; height: 30px; text-align: center; line-height: 30px;}
    </style>
    <script>
        function download(res){
            var oT1 = document.getElementById("t1");
            var oInfor = document.getElementById("infor");

            oInfor.innerHTML = `城市:${res.city},PM2.5:${res.pm25},日期:${res.date}`;
            var we = res.weather;
            var showContent =``;
            for(var i = 0; i < we.length; i++){
                var showContent = showContent + `
                                                <tr>
                                                    <td>${we[i].date}</td>
                                                    <td>${we[i].weather}</td>
                                                    <td>${we[i].wind}</td>
                                                    <td>${we[i].temp}</td>
                                                </tr>
                                                `;
            }
            oT1.innerHTML = showContent;
        }
    </script>
    <!-- <script>调用位置</script> -->
    <script id="callFun">
        /*
            天气查询:

                
        */
        window.onload = function(){
            var oSearch = document.getElementById("search");
            var location = document.getElementById("callFun");
            var oCity = document.getElementById("cityName");

            oSearch.onclick = function(){
                if(!oCity.value){
                    alert("请输入需要查询的城市!");
                }else{
                    var oScript = document.createElement("script");
                    oScript.src = `https://api.asilu.com/weather/?city=${oCity.value}&callback=download`;
                    document.head.insertBefore(oScript, location);
                }
            }
            
        }
    </script>
</head>
<body>
    <div class="container box">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <h2>天气查询
                    <span id="infor"></span>
                </h2>
            </div>
            <div class="panel-body">
                <div class="form-group">
                    <label for = "city">城市名称:</label>
                    <input type="text" class="form-control" id="cityName">
                    <button class="btn btn-primary form-control" id="search">确定</button>
                </div>
            </div>
            <div class="panel-footer">
                <table class="table table-bordered table-hover">
                    <thead>
                        <tr>
                            <td>日期</td>
                            <td>天气</td>
                            <td>风向</td>
                            <td>气温</td>
                        </tr>
                    </thead>
                    <tfoot id="t1"></tfoot>
                </table>
            </div>
        </div>
    </div>
</body>
</html>
View Code

  2. 百度搜索框

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{margin: 0px; padding: 0px;} 
        #box{  800px; height: 600px; border: black solid 3px; margin: 50px auto;}
        #ins{  300px; height: 50px; border: solid 1px; margin-top:100px; margin-left: 250px;
            display: block; font-size: 30px;}
        #list{ margin-left: 250px; list-style: none;font-size: 30px;}
        #list li{  300px;}
        #list li:hover{ background-color: blanchedalmond;}
    </style>
    <script>
        function show(res){
            var oS = res.s;
            var oList = document.getElementById("list");
            oList.innerHTML = "";
            oList.style.display = "block";
            
            var Content = ``;
            for(var i = 0; i < oS.length; i++){
                var newLi = document.createElement("li");
                var oA = document.createElement("a");
                oA.innerHTML = oS[i];
                oA.href = `http://www.baidu.com/s?wd=` + oS[i];
                oA.target = "_blank";

                newLi.appendChild(oA);
                oList.appendChild(newLi);
            }
            
        }
    </script>
    <script id="callFun">
        window.onload = function(){
            var oIns = document.getElementById("ins");
            var location = document.getElementById("callFun");
            var oList = document.getElementById("list");


            oIns.onkeyup = function(){
                var oValue = ins.value;
                if(!oValue){
                    oList.style.display = "none";
                }else{
                    var oScript = document.createElement("script");
                    oScript.src = `http://suggestion.baidu.com/su?wd=${oValue}&cb=show`;
                    document.head.insertBefore(oScript, location);
                }
            }


        }
    </script>
</head>
<body>
    <div id="box">
        <input type="text" id="ins">
        <ul id="list"></ul>
    </div>
</body>
</html>
View Code
原文地址:https://www.cnblogs.com/carreyBlog/p/13232737.html