1,什麼是跨域?
跨域跨域,跨過域名,籠統來說就是一個域名區請求另外一個域名的數據,但實際上,不同端口、不同域名、不同協議上請求數據都會出現跨域問題。瀏覽器出於安全考慮會報出異常,拒絕訪問。
2,jsonp的原理?
jsonp(json with padding)是一種十分常見的實現跨域請求的手段,利用src屬性能跨域請求的特點來實現。
比如:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
這段代碼就實現了引用jQuery的功能,請求成功後返回jQuery的源碼。不止script標籤,audio,img標籤都能 進行跨域請求並且不被瀏覽器攔截。
想要使用jquery裏的方法,就必須引入jquery,換句話說,必須要有這個方法,然後我們才能使用
比如:引用jquery,來實現點擊變色的效果:
<body> <div id="app">點擊變色</div> <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script> <script type="text/javascript"> $('#app').click(function() { this.style.color = 'red' }) </script> </body>
這裏可以看到,引用完Jq之後就能調用它封裝好的click方法。
也就是說,我們可以提前定義一個包含參數的方法,然後調用的時候把數據當做實參傳入就能實現對數據的操作
<script type="text/javascript"> function who(r){ console.log(`我的名字是${r}`) } </script> <script type="text/javascript"> who("小明") </script>
再深入一點,我們在前臺定義一個函數,然後請求後端返回這個函數的調用
現在有一個數據爲person,返回給前臺使用。
server.js文件裏的代碼:請求時會返回 一個回調函數 who(小明)
const http =require("http");
http.createServer((req,res)=>{
var person='小明'
res.write(`who("${person}")`)
res.end()
}).listen(3003)
index.html文件裏的代碼:
<body> <script type="text/javascript">
function who(r){
console.log(`我的名字是${r}`)
}
</script>
<script src="http://localhost:3003"></script>//請求成功後則執行 who(小明)
</body>
輸出結果:
如此一來,就實現了一個簡單的跨域獲取數據的操作。
3,怎麼實現jsonp?
jsonp的實現很簡單,就是動態創建一個script標籤
比如:點擊按鈕獲取後臺數據 後臺代碼同上面的server.js
<body>
<button id="btn">點擊獲取數據</button>
<p id="text"></p>
<script type="text/javascript">
function who(r) {
document.getElementById('text').innerText = r
}
document.getElementById("btn").addEventListener("click", () => {
var script = document.createElement("script")
script.src = "http://localhost:3003"
document.body.appendChild(script)
document.querySelector("body script:last-child").remove()
})
</script>
<!-- <script src="http://localhost:3003"></script> -->
</body>
這樣寫存在一個弊端,就是前後端必須嚴格的統一,設定好回調函數名稱,比如這裏回調函數都爲 who()
前臺只需重新設置下src的值
script.src = "http://localhost:3003?callback=getName"
後臺獲取傳入的callback的值然後重新拼接,
res.write(`${callback}("${person}")`)
- 最後再記錄一下jquery中jsonp的使用
$.ajax({ type: 請求方式get|post, url: 請求地址, dataType: "jsonp",//最關鍵的一步,使用jsonp jsonp: "callback",//回調函數的參數名,默認爲callback jsonpCallback: "callBackFun",//回調函數的函數名
/*
例如這裏
jsonp:myCallback
jsonpCallback:getName
則請求地址爲http://localhost:3003?myCallback=getName
*/
success:function(){ console.log(this) }, error:function(){ console.log("error"+this) }
})
查看更多內容請訪問:根號七的網站