原理:首先客戶機會注冊一個callback,在發送跨域請求之前,會在url后附帶注冊的callback參數(如:callback1982342322),隨后服務器拿到了callback參數,獲取數據后再拼接json數據(如:callback1982342322({status:"ok",fantasy [{ key:value }] }) ),此處應該注意服務器拿到的callback要和客戶機上的callback一致,否則跨域不成功,用chrom瀏覽器可發現 callbackxxx is not defined
1. 客戶端跨域請求json數據方式
- $.ajax( type , async , url , dataType , jsonp ,success : function(json){expression...} , error : function(){expression...})
這里說明一點,就是jquery是不支持post方式的跨域請求
- $.getJSON( url , param , function(json){ expression ... })
2. 服務器端設置
參數: callback / param...
響應: callback({
status:"ok",
fantasy[{
key1:value1,
key2:value2
}]
});
3. 錯誤
收集了測試和實戰過程中出現的一些錯誤
1.Origin null is not allowed by Access-Control-Allow-Origin 不支持本地Ajax請求 2.jquery12334223232 is not defined 沒有注冊callback參數,利用谷歌瀏覽器的開發者工具查看跨域請求里是否含有callback參數和值,然后檢查服務器是否接收 callback參數並拼接成json格式的數據響應給客戶機 3.XMLHttpRequest cannot load http://i.nubb.com/fcms/conn/shareToFantasy.htm?fid=11&callback=jsoncallback102131211. Origin http://fantasy.nubb.com is not allowed by Access-Control-Allow-Origin. 解決方法:選定google瀏覽器快捷方式右鍵 -> 屬性 -> 目標(T) -> 加上 --disable-web-security (如:"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security)
4. 實例:
<script type="text/javascript"> jQuery(document).ready(function(){ $.ajax({ type: "get", async: false, url: "http://i.nubb.com/fcms/conn/shareToFantasy.htm?fid=<%=team.getFans_id()%>&format=jsonp", dataType: "jsonp", jsonp: "callback",//傳遞給請求處理程序或頁面的,用以獲得jsonp回調函數名的參數名(一般默認為:callback) success: function(json){ //dom生成數據 for(var num in json.fantasy){ var html = "<div class=\"tao\"><div class=\"tao1\"><span class=\"t\">" +"<p><span>$qc-read</span><a href=\"#\"><img src=\"/images/sd_career/liu.gif\" /> </a></p>" +"</span><div class=\"wenzi\">" +"<h3>$qc-title</h3>" +"<div class=\"d\">" +"<p><a href=\"http://i.nubb.com/fans/Topicdetail.htm?fid=$qc-fid&aid=$qc-aid\" target=\"_blank\">$qc-desc</a>" +"<dl>" +"<dt><a href=\"javascript:;\" target=\"_blank\"><img src=\"http://i.nubb.com$qc-ulogo\" /></a></dt>" +"<dd><a href=\"http://i.nubb.com/home/$qc-uid.htm\" target=\"_blank\">$qc-uname</a> <span id=\"qc-time\">發布於 $qc-time</span></dd>" +"</dl>" +"</p></div></div></div></div>"; console.log(json.fantasy[num]); html = html.replace("$qc-aid", json.fantasy[num].aid); html = html.replace("$qc-fid", <%=team.getFans_id()%>); html =html.replace("$qc-read", json.fantasy[num].read); html =html.replace("$qc-title", json.fantasy[num].title); html =html.replace("$qc-desc", json.fantasy[num].desc); html =html.replace("$qc-uid", json.fantasy[num].uid); html =html.replace("$qc-uname", json.fantasy[num].uname); html =html.replace("$qc-ulogo", json.fantasy[num].ulogo); html =html.replace("$qc-time", json.fantasy[num].time.substring(0,10)); $(".taolun").append(html); } }, error: function(){ console.log('非法請求'); } }); }); </script>