本文介绍: 使用JSONP解决跨域(JS中、Jquery里边的Ajax

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

什么是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" /&gt;
    <title&gt;Document</title&gt;
  </head&gt;
  <body&gt;
  
    <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&amp;p=3&amp;ie=utf-8&amp;json=1&amp;prod=pc&amp;from=pc_web&amp;sugsid=36067,36175,31254,34812,36165,34584,36141,36120,36194,36126,35802,35317,26350,36112,35868,36061&amp;wd=" +a + "&amp;req=2&amp;bs=12&amp;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.phpkey=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=
  */

原文地址:https://blog.csdn.net/Lnbd_/article/details/123921804

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_26596.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注