【使用JSONP解决跨域(JS中、Jquery里边的Ajax)】

一、使用JSONP来解决跨域分为以下两种

  • JS来解决
  • Jquery里边的Ajax来解决

什么是JSONP跨域

JSONP是一种解决跨域问题的方法,并不是一种数据格式(不同于JSON),是一种绕过同源策略实现跨域获取数据的解决方案,是一种非正式传输协议

同源策略
要实现跨域,必须知道什么是同源策略?

同源策略是一种安全策略,所有支持JavaScript的浏览器都会使用同源策略

同源是指协议、端口、域名相同,不同源将无法请求到对应数据

http://www.abc.com/other.html:同源
https://www.abc.com/other.html:不同源(协议不同)
http://v2.www.abc.com/other.html:不同源(域名不同)
http://www.abc.com:81/other.html:不同源(端口不同)

二、使用JS解决JSONP跨域

第一步 在文件夹里边新建index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
  
    <h1>jsonp跨域</h1>
    <button id="btnid">跨域请求按钮</button>
    <ul></ul>  //ul是即将展示跨域之后获取到的内容
    
    <script>
      var btnid = document.getElementById("btnid");  //获取button按钮
      var oul = document.getElementsByTagName("ul")[0];
      // let _url = "https://mbd.baidu.com/newspage/api/getusername?cb=callback = datafn"
                                                                       //键值对或者是赋值
      
      btnid.onclick = function () {   //给button绑定一个事件
        let a = Math.ceil(Math.random() * 100);   
    //a的值会自动生成一个随机数,Math.ceil()向上取整; Math.random() * 100 随机数从零到一百里边
        let servers = document.createElement("script");  //动态创建一个Script标签属性
        servers.src ="https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=36067,36175,31254,34812,36165,34584,36141,36120,36194,36126,35802,35317,26350,36112,35868,36061&wd=" +a + "&req=2&bs=12&pbs=12&csor=2&pwd=12&cb=callback=datafn";
         
        //如果我想把  servers.src  里边的接口换成别的(比如说 搜狐、百度、微博)那我后面的参数改怎么拼接,如果说是 a     callback这两个  ,对这个接口是怎么看出来的
        servers.type = "text/javaScript";
        document.getElementsByTagName("body")[0].appendChild(servers);
        document.getElementsByTagName("body")[0].removeChild(servers);
      };

      function datafn(data) {
        console.log(data)
    
        oul.innerHTML = "";
        //获取到的值
        let datas = data.g;
        // console.log(datas);
        datas.forEach(function (el) {
          var oli = document.createElement("li");
          oli.innerHTML = el.q;
          oul.appendChild(oli);
        });
      }
    </script>
  </body>
</html>

三、使用Jquery来进行JSONP跨域

第一步: 先将jquery包下载下来

npm install Jquery

下载成功后的效果
在这里插入图片描述

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./node_modules/jquery/dist/jquery.js"></script>  //引入jquery
  </head>
  <body>
    <button>获取数据</button>
    <button>百度</button>
    <h3>百度</h3>
    <h2>360</h2>
    <h4>搜狐</h4>
    <!-- <h5>微博</h5> -->
    <script>
      //   百度
       $(function () {
        $("h3").click(function () {
         let b =  document.cookie="pin=test;domain=test.com";
         console.log(b);
          let a = Math.ceil(Math.random() * 100);
          $.ajax({
            type: "get",
            url:
              "https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=36067,36175,31254,34812,36165,34584,36141,36120,36194,36126,35802,35317,26350,36112,35868,36061&wd=" +
              a +
              "",
            dataType: "jsonp",
            jsonp: "cb",
            xhrFields: { withCredentials: true },  //让他携带上cookie
            success: function (cname) {
              console.log(cname);
              
             
            },
          });
        });
       });

      //   360    https://login.360.cn/?callback=jQuery1830009746163947829345_1648779940633&src=pcw_so&from=pcw_so&charset=UTF-8&requestScema=https&quc_sdk_version=6.9.2&quc_sdk_name=jssdk&o=User&m=checkmobile&mobile=17395915861&type=&_=1648780158508
      
      $(function () {
        //   console.log(111);
        $("h2").click(function () {
          // console.log(this.value);
          let a = Math.ceil(Math.random() * 100);
          $.ajax({
            type: "get",
            url:
              "https://sug.so.360.cn/suggest?encodein=utf-8&encodeout=utf-8&format=json&src=so_home&fields=word&word=" +
              a +
              "",
            dataType: "jsonp",
            // jsonp:"cb",
            success: function (res) {
              console.log(res);
              //下边是循环,如果需要的话可以打开
              // res.result.forEach(el => {
              //     console.log(el.word);
              // });
            },
          });
        });
      });

      //   搜狐
      $(function () {
        //   console.log(111);
        $("h4").click(function () {
          // console.log(this.value);
          let a = Math.ceil(Math.random() * 100);
          $.ajax({
            type: "get",
            url: "https://search.sohu.com/search/v2/suggest?keyword=" + a + "",
            dataType: "jsonp",
            // jsonp:"cb",
            success: function (res) {
              console.log(res);
              // res.result.forEach(el => {
              //     console.log(el.word);
              // });
            },
          });
        });
      });
    </script>
  </body>
</html>

/*

  微博 https://s.weibo.com/ajax/topsuggest.php?key=2&_k=1648776420293&_t=1&outjson=1&uid=0
   搜狐 https://search.sohu.com/search/v2/suggest?keyword=1


  "https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=36067,36175,31254,34812,36165,34584,36141,36120,36194,36126,35802,35317,26350,36112,35868,36061&wd="+a+""
  https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=36067,36175,31254,34812,36165,34584,36141,36120,36194,36126,35802,35317,26350,36112,35868,36061&wd=a&req=2&bs=a&csor=1&cb=
 
  百度 let url = "https://www.baidu.com/sugrec?pre=1&p=3&ie=utf-8&json=1&prod=pc&from=pc_web&sugsid=36067,36175,31254,34812,36165,34584,36141,36120,36194,36126,35802,35317,26350,36112,35868,36061&wd=12"
                                                            //
 360 let url = "https://sug.so.360.cn/suggest?encodein=utf-8&encodeout=utf-8&format=json&src=so_home&fields=word&word=a"

 https://sug.so.360.cn/suggest?callback=suggest_so&encodein=utf-8&encodeout=utf-8&format=json&src=so_home&fields=word&word=a&huid=11Ajxnj02GnK5MftYlIvGx8rGUHjjoNZrqk8%2F%2Bv%2F0bMXE%3D&llbq=A5%2CB5%2CC5%2CD5&cache=&id=
  */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值