1. 程式人生 > >Jsonp

Jsonp

post class state 發送請求 pca 定義 json -- get

在需要訪問不同域的接口的數據的時候,一般有兩種方式:

第一種:使用requests模塊,在業務邏輯中直接訪問別的域的接口,獲取數據,然後將返回的數據顯示到前端頁面上;

這個時候,訪問的流程是: 客戶端-->server請求其他域的接口--->返回數據到server--->返回到客戶端

import requests

def req(request):
    response = requests.get(‘http://php.weather.sina.com.cn/xml.php?city=%B1%B1%BE%A9&password=DJOYnieT8234jlsK&day=0‘)
    # print(response.content)   #字節
    response.encoding = ‘utf-8‘
    # print(response.text)       #字符串
    return render(request,‘req.html‘,{‘result‘:response.text})

第二種:使用js直接請求別的域的接口,獲取數據,最長用的是jsonp;

    <h1>後臺獲取的結果</h1>
    {{ result }}
    <h1>js獲取的結果</h1>
    <input type="button" value="獲取數據" onclick="getContent();">
    <div id="container"></div>
    <script>
        function getContent() {
            /*
            var xhr = new XMLHttpRequest();
            xhr.open(‘GET‘,‘http://php.weather.sina.com.cn/xml.php?city=%B1%B1%BE%A9&password=DJOYnieT8234jlsK&day=0‘);
            xhr.onreadystatechange = function () {
                console.log(xhr.responseText);
            };
            xhr.send()
            */
            var tag = document.createElement(‘script‘);
            tag.src = ‘http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list_=145376870403‘;   //在創建src屬性的時候,就會發送請求
            document.head.appendChild(tag);
            document.head.removeChild(tag);
        }

        function list(arg) {
            console.log(arg);
        }
    </script>

jsonp請求的原理:瀏覽器具有同源策略,對於ajax請求,不接受不同域的數據,而對於script標簽沒有此約束,在創建script標簽的src屬性的時候,頁面在加載src的鏈接的時候,也會執行(發送鏈接的請求)鏈接的地址,如果鏈接是http get的接口,會返回對應的數據,這樣就實現了獲取不同域的接口的數據的目的;

需要註意的是:接口返回的數據,一定要符合js格式,否則數據沒有辦法被處理,一般我們在src的get請求鏈接,會攜帶參數?callback=list,使用callback表示需要被返回的數據的格式,這樣就可以在定義專門處理返回的數據的方法了; jsonp只能發送get請求,不能發送其他的請求;

使用jquery+jsonp請求數據如下:

        function list(arg) {
            console.log(arg);
        }

        function getContent() {
            $.ajax({
                url : ‘http://www.jxntv.cn/data/jmd-jxtv2.html?callback=list_=145376870403‘,
                type : ‘POST‘,
                dataType: ‘jsonp‘,
                jsonp: ‘callback‘,
                jsonpCallback:‘list‘
            })
        }

  

第三種:cors:跨域資源共享,就是在server端設置響應頭來實現的;

參考博客:http://www.cnblogs.com/wupeiqi/articles/5703697.html

Jsonp