zoukankan      html  css  js  c++  java
  • jsonp实现跨域请求

    直接用原生ajax请求另一个域的资源,会被同源策略限制,而用<script src="url"></script>这种方式“引入url”,实际上引入了一个js代码,就不会被同源策略限制,可以请求到。

    用这个有一个前提就是对方网站后台的返回确实设置了js代码块或者某个callback函数,所以这种请求方式是有特定应用场景的,并不是跨域都能用这种。

    1. javascript方式

        <script>
            function getContent() {
                /* 原生ajax会被同源限制
                var xhr = new XMLHttpRequest();
                xhr.open('GET','http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101121301');
    
                xhr.onreadystatechange = function () {
                  console.log(xhr.responseText);
                };
                xhr.send();
                
                var tag = document.createElement('script');
               tag.src = 'http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101121301';#}
               document.head.appendChild(tag);
           document.head.removeChild(tag);
            }
            
            /* 回调函数,这个得看api的写法,有的是动态的,有的是写死的。 */
            function list(arg) {
                console.log(arg)
            }
        </script>
    

    2. jquery ajax

    用这种<script src>引入的方式的话,是不用发POST请求的,因为ajax如下的配置实际上就做了如上的事,也是封装了引入方式,所以最终ajax写POST请求会变为GET请求发送。

    $.ajax({
           url:'http://weatherapi.market.xiaomi.com/wtr-v2/weather?cityId=101121301',
        //这儿写GET,POST都一样,最后都发的是GET请求。
           type:'POST',
           dataType:'jsonp',
           jsonp:'callback',
           jsonpCallback:'list',
    })    
  • 相关阅读:
    CodeForces 734F Anton and School
    CodeForces 733F Drivers Dissatisfaction
    CodeForces 733C Epidemic in Monstropolis
    ZOJ 3498 Javabeans
    ZOJ 3497 Mistwald
    ZOJ 3495 Lego Bricks
    CodeForces 732F Tourist Reform
    CodeForces 732E Sockets
    CodeForces 731E Funny Game
    CodeForces 731D 80-th Level Archeology
  • 原文地址:https://www.cnblogs.com/NoYone/p/8270831.html
Copyright © 2011-2022 走看看