部落客以前覺得隻要知道jsonp是通過src屬性來實作跨域的就行了,但是,發現最終吃虧的永遠是自己,于是部落客準備從今天開始,不再隻是涉獵,應該去好好品嘗其中滋味~
-
首先要明确用戶端與伺服器端通信的原理:
如下:本地的程式通過script标簽請求伺服器端的檔案
<html> <body> <script src="http://remoteserver.com/remote.js"></script> <script type="text/javascript"> var localHandler=function(data){ console.log(data.result); } </script> </body> </html>
remote.js
伺服器端調用用戶端的函數
localHandler({ "result":"伺服器端資訊" })
-
知道如何通信之後,如何動态建立一個通路服務端的請求呢?
當然就要涉及動态建立script标簽,建立完了記得加入到文檔中去哦
<html> <head> </head> <body> <script> var handler=function(data){ console.log(data.price); }; var url="http://a.com/1.aspx?code=11&callback=Handler"; var script = document.createElement('script'); script.setAttribute('src',url); document.getElementByTagName('body')[].appendChild(script); </script> </body> </html>
-
jquery又如何使用jsonp跨域呢?
首先在jquery中,jsonp是歸于ajax的,而且會自動生成回調函數
<html> <body> <script src="jquery.min.js"></script> <script type="text/javascript"> jQuery(document).ready(function(){ $.ajax({ type:"get", async:false, url="http://a.com/1.aspx?code=11&callback=Handler", dataType:'jsonp', jsonp:"callback", jsonpCallback:'Handler',//此處可以不寫,jquery會自動聲生成函數,幫你處理資料 success:function(json){ console.log(json.price); }, error:function(){ alert('error'); } }) }) </script> </body> </html>