Stories

Detail Return Return

php實現callback跨域請求jsonp數據 - Stories Detail

摘要

JSONPJSON with Padding 的縮寫,是一種解決跨域數據獲取的方案。由於瀏覽器的同源策略限制,不同域名之間的前端JS代碼不能相互訪問到對方的數據,JSONP通過script標籤的特性,實現在不同域名的網頁間傳遞數據。

其原理是在客户端頁面上定義一個回調函數 (callback),然後通過script標籤向外部服務器請求數據,並將定義好的回調函數名稱作為參數放在url請求地址裏,服務器成功接收請求後,使用該參數將數據傳遞給定義好的回調函數並返回,客户端頁面中定義好的回調函數接收參數後進行處理。

正常的AJAX請求

$.ajax({
    url: "https://qq.com/getdata/",
    success: function(res) {
        console.log(res)
    }
});

如果跨域請求,瀏覽器會報錯:

跨域:例如你訪問頁面的域名是 https://baidu.com/getdata/,但是ajax請求的是 https://qq.com/getdata/ ,雖然都是getdata,但是其域名不一樣,瀏覽器會拒絕請求。

這樣的情況下,你通過ajax是無法獲得請求數據的。

如何解決這個問題?jsonp就可以解決。

JSONP數據源代碼示例

數據源即ajax請求的接口,其返回的是由括號括起來的json數據。服務端需要根據請求中的回調函數名稱callback,將用户數據包裝在函數調用中。

假設是:https://www.qq.com/callbackData/index.php

<?php

    // 頁面編碼
    header("Content-type:application/json");
    
    // 數據源
    $data = array(
        array(
            'title' => '90後考上公職3個月開始貪污獲刑3年',
            'url' => 'https://baijiahao.baidu.com/s?id=1780086209787359686'
        ),
        array(
            'title' => '男子閃婚後閃離 24萬彩禮要回8萬',
            'url' => 'http://dzb.hxnews.com/news/kx/202310/19/2138573.shtml'
        ),
        array(
            'title' => '神舟十七號船箭組合體轉運至發射區',
            'url' => 'https://baijiahao.baidu.com/s?id=1780150004201916038&wfr=spider&for=pc'
        ),
        array(
            'title' => '以色列要求本國公民立即離開土耳其',
            'url' => 'https://baijiahao.baidu.com/s?id=1780107306390790504&wfr=spider&for=pc'
        ),
        array(
            'title' => '好萊塢將翻拍《你好李煥英》',
            'url' => 'https://baijiahao.baidu.com/s?id=1780164746410232029&wfr=spider&for=pc'
        )
    );
    
    // 返回結果
    $result = array(
        'datalist' => $data,
        'code' => 200,
        'msg' => '獲取成功'
    );

    // 輸出callback
    $resultCallback = json_encode($result);
    echo $_GET['callback'] . "(" . $resultCallback . ")";
    
?>

ajax請求

<html>
    <head>
        <title>jsonp請求示例</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0,viewport-fit=cover">
        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    </head>
    
    <body>
        
        <div id="app"></div>
        <script>
            $.ajax({
                url: "https://www.qq.com/callbackData/index.php",
                dataType: "jsonp",
                jsonpCallback: "handleJSONPResponse",
                success: function(res) {
                    
                    console.log(res)
                }
            });
        </script>
    </body>
</html>

結果:

image.png

通過 dataType: "jsonp" 就可以成功請求到數據。

服務器&主機推薦

免備案的虛擬主機、雲服務器
寶塔/EP系統預裝(支持Windows),一鍵式操作
https://www.rainyun.com/TANKING_

作者

TANKING

user avatar grewer Avatar code2roc Avatar zzd41 Avatar romanticcrystal Avatar tanggoahead Avatar hyfhao Avatar zhaodawan Avatar shuyuanutil Avatar nzbin Avatar chiqingdezhentou Avatar jungang Avatar hezuidedianti_dpqcuq Avatar
Favorites 39 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.