具體策略限制情況可看下表:
URL | 說明 | 允許通信 |
---|---|---|
http://www.a.com/a.js
http://www.a.com/b.js |
同一域名下 | 允許 |
http://www.a.com/lab/a.js
http://www.a.com/script/b.js |
同一域名下不同文件夾 | 允許 |
http://www.a.com:8000/a.js
http://www.a.com/b.js |
同一域名,不同端口 | 不允許 |
http://www.a.com/a.js
https://www.a.com/b.js |
同一域名,不同協(xié)議 | 不允許 |
http://www.a.com/a.js
http://127.0.0.100/b.js |
域名和域名對應ip | 不允許 |
http://www.a.com/a.js
http://script.a.com/b.js |
主域相同,子域不同 | 不允許 |
http://www.a.com/a.js
http://a.com/b.js |
同一域名,不同二級域名(同上) | 不允許 |
http://www.a.com/a.js
http://www.b.com/b.js |
不同域名 | 不允許 |
JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式,而JSONP(JSON with Padding)則是JSON 的一種“使用模式”,通過這種模式可以實現(xiàn)數(shù)據(jù)的跨域獲取。
舉個例子,假如需要從服務器(http://www.a.com/user?id=123)獲取的數(shù)據(jù)如下:
那么,使用JSONP方式請求(http://www.a.com/user?id=123?callback=foo)的數(shù)據(jù)將會是如下:
- {"id": 123, "name" : 張三, "age": 17}
當然,如果服務端考慮得更加充分,返回的數(shù)據(jù)可能如下:
- foo({"id": 123, "name" : 張三, "age": 17});
- try{foo({"id": 123, "name" : 張三, "age": 17});}catch(e){}
這時候我們只要定義一個foo()函數(shù),并動態(tài)地創(chuàng)建一個script標簽,使其的src屬性為http://www.a.com/user?id=123?callback=foo:
function executeJsonp(url){ var eleScript= document.createElement("script"); eleScript.type = "text/javascript"; eleScript.src = url; document.getElementsByTagName("head")[0].appendChild(eleScript); } function foo(data){ for(var p in data){ console.log(data[p]); } } var url = "http://www.a.com/user?id=123?callback=foo"; executeJsonp(url)便可以使用foo函數(shù)來調用返回的數(shù)據(jù)了。
第二種方法是利用getJSON來實現(xiàn),只要在地址中加上callback=?參數(shù)即可:
- $.ajax({
- dataType: 'jsonp',
- url: 'http://www.a.com/user?id=123',
- success: function(data){
- //處理data數(shù)據(jù)
- }
- });
- $.getJSON('http://www.a.com/user?id=123&callback=?', function(data){
- //處理data數(shù)據(jù)
- });
也可以簡單地使用getScript方法:
- //此時也可以在函數(shù)外定義foo方法
- function foo(data){
- //處理data數(shù)據(jù)
- }
- $.getJSON('http://www.a.com/user?id=123&callback=foo');
JSONP在開放API中可以起到非常重要的作用,開放API是運用在開發(fā)者自己的應用上,而許多應用往往是在開發(fā)者的服務器上而不是在新浪微博的服務器上,因此跨域請求數(shù)據(jù)成為開發(fā)者們所需要解決的一大問題,廣大開放平臺應該實現(xiàn)對JSONP的支持,這一點新浪微博開放平臺便做的非常好(雖然某些API里沒有說明,但實際上是可以使用JSONP方式調用的)。
使用GET方式和POST方式都可以進行跨域調用
客戶端代碼
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function aa() {
$.ajax({
url: "http://localhost:12079/WebForm2.aspx",
data: "p1=1&p2=2&callback=?",
type: "post",
processData: false,
timeout: 15000,
dataType: "jsonp", // not "json" we'll parse
jsonp: "jsonpcallback",
success: function(result) {
alert(result.value1);
}
});
}
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
<p>
<input id="Button1" type="button" value="button" onclick="aa()" /></p>
</body>
</html>
服務器端代碼
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string callback = Request["callback"];
string v1="1";
string v2="2";
string response = "{\"value1\":\"" + v1 + "\",\"value2\":\"" + v2 + "\"}";
string call = callback + "(" + response + ")";
Response.Write(call);
Response.End();
}
}
客戶端頁面和服務器端頁面在兩個項目中,以便進行跨域調用測試。
跨域實例代碼(需要加載jquery,頁面為utf-8編碼):
<!--拉勾招聘數(shù)據(jù)-->
<script type="text/javascript">
function success_jsonpCallback(data){
var html = '';
var pos = '';
html += '<ul>';
jQuery.each(data, function(k, v) {
if(k<10){
pos = '【' + v.city+ '】' + v.positionName + '('+ v.salary +') - '+v.companyName;
if(pos.length > 20){
pos = pos.substring(0,19)+'...';
}
html += '<li><a href="'+v.posiitonDetailUrl+'" target="_blank" title="【' + v.city+ '】' + v.positionName + '('+ v.salary +') - '+v.companyName+'">'+pos+'</a></li>';
}
});
html += '</ul><div class="more-link"><a rel="external nofollow" target="_blank" target="_blank">更多</a></div>';
jQuery('#lagouData').html(html);
}
function getLagouData() {
jQuery.ajax({
async:false,
url: "http://www.lagou.com/join/listW3cplus?kd=%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91",
type: "GET",
dataType: "jsonp",
jsonpCallback: 'success_jsonpCallback',
contentType: "application/jsonp; charset=utf-8",
success: function(data) {
success_jsonpCallback(data);
}
});
}
getLagouData();
</script>
<div id="lagouData"></div>
jsonp代碼:
success_jsonpCallback([{"city":"廣州","companyName":"POCO.CN","createTime":"15:02發(fā)布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/16868.html","positionAdvantage":"身處凝聚力團隊,老城區(qū)上班交通便利,雙休","positionName":"商業(yè)前端開發(fā)工程師","salary":"4k-7k"},{"city":"北京","companyName":"美通云動(北京)科技有限公司","createTime":"14:47發(fā)布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/16866.html","positionAdvantage":"Html5技術最棒的團隊","positionName":"Web前端開發(fā)","salary":"4k-8k"},{"city":"杭州","companyName":"口袋購物","createTime":"14:42發(fā)布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/13024.html","positionAdvantage":"廣闊的發(fā)展平臺、自我價值體現(xiàn)的地方","positionName":"web前端開發(fā)工程師","salary":"8k-12k"},{"city":"北京","companyName":"布丁移動","createTime":"14:02發(fā)布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/1498.html","positionAdvantage":"三餐、周圍美女如云","positionName":"Android開發(fā)工程師","salary":"10k-20k"},{"city":"北京","companyName":"布丁移動","createTime":"14:02發(fā)布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/2539.html","positionAdvantage":"三餐,小橋流水人家,美女","positionName":"ios開發(fā)工程師","salary":"10k-20k"},{"city":"上海","companyName":"天天動聽","createTime":"00:55發(fā)布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/11494.html","positionAdvantage":"創(chuàng)業(yè)氛圍 講求小而美","positionName":"Android開發(fā)工程師","salary":"8k-16k"},{"city":"北京","companyName":"LBE安全大師","createTime":"11:39發(fā)布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/5983.html","positionAdvantage":"五險一金 績效獎金","positionName":"Android開發(fā)工程師","salary":"8k以上"},{"city":"北京","companyName":"點心移動","createTime":"11:24發(fā)布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/16736.html","positionAdvantage":"技術導向的團隊氛圍,全方位的福利待遇","positionName":"Android","salary":"15k-25k"},{"city":"廣州","companyName":"荔枝FM","createTime":"10:44發(fā)布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/16634.html","positionAdvantage":"連堅持跑步、保持體重都有獎勵哦!","positionName":"WP手機開發(fā)工程師","salary":"16k-25k"},{"city":"北京","companyName":"網(wǎng)銀-京東子公司","createTime":"10:08發(fā)布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/14162.html","positionAdvantage":"負責京東商城-互聯(lián)網(wǎng)金融產品 JS開發(fā)","positionName":"Javascript 前端開發(fā)工程師","salary":"10k-20k"}])
更多建議: