前言
由于瀏覽器有同源策略,所以要想獲取非同源(協(xié)議,域名,端口三者有一不同都算非同源)的頁面的數(shù)據(jù),就得進行跨域
(1) jsonp原理
由于script標(biāo)簽的src屬性可以訪問非同源的js腳本,所以通過src屬性訪問服務(wù)器會返回函數(shù)的js代碼,而我們想要的數(shù)據(jù)就作為函數(shù)參數(shù)返回,而我們會先定義這個函數(shù),返回的js代碼就可執(zhí)行
(2) jsonp實現(xiàn)代碼
請求頁面
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> function jsonp(data){ console.log(username) } </script> <script type="text/javascript" src="jquery-1.8.3.min.js"> </script> <script type="text/javascript"> $(document).ready(function(){ var url = "http://www.example.com/jsonp.php?callback=jsonp"; var script = $('<script><\/script>'); script.attr("src",url); $("body").append(script); }); </script> </body> </html>
<?php $data = {'name': '張三'}; $callback = $_GET['callback']; echo $callback."(".json_encode($data).")"; ?php>
之后php會返回
jsonp({ name:'niuni })
然后PHP返回的代碼h會被請求頁面的jsonp方法執(zhí)行
(3)jQuery的簡便jsonp跨域
<script> function showData (data) { console.info(data); } $(document).ready(function () { $("#btn").click(function () { $.ajax({ url: "http://www.example.comjsonp", type: "GET", dataType: "jsonp",// 返回數(shù)據(jù)類型 jsonpCallback: "showData",//回調(diào)函數(shù) // 獲取數(shù)據(jù)成功就執(zhí)行success函數(shù) success: function (data) { console.info("data"); } }); }); }); </script>
總結(jié)
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com