客户端js无需任何专门设置,使用通常的ajax调用即可:
$.ajax({ url: '跨域URL', type: 'get', dataType: 'json', success: function (data) { $('#banner_right').html(data); } });
服务端需要在WebApiConfig.Register()中添加如下的代码
public static class WebApiConfig { public static void Register(HttpConfiguration config) { var cors = new EnableCorsAttribute("http://www.cnblogs.com,http://news.cnblogs.com", "*", "*"); config.EnableCors(cors); } }
注1:"http://www.cnblogs.com,http://news.cnblogs.com"表示允许这2个域名可以跨域调用这个Web API。
注2:需要nuget安装Microsoft.AspNet.Cors
http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-05.html
“NO,you can't”,这个是最简单的问题。
但是也不是没有变通的方式,通过代理服务器原理,将你的请求通过代理服务器(可以是任意域名,可以跨域)去访问,代理服务器处理这个请求,并且“在响应的标头中加上Access-Control-Allow-Origin:*”,最后输出内容给客户端。你可以自己实现简单的代理。googling了下,CORS
http://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work
这,http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
https://msdn.microsoft.com/en-us/magazine/dn532203.aspx
太多了点吧。。。
jsonp
dudu大人提问,不都应该是高分吗?哈哈,自己印钱.
jsonp,貌似百度搜索的搜索提示,就是这样搞的.
jQuery110207612842570524663_1440600764863({ "q": "jsonp", "p": false, "bs": "", "csor": "5", "g": [{ "q": "json", "t": "n", "st": { "q": "json", "new": 0 } }, { "q": "jsonp 跨域", "t": "n", "st": { "q": "jsonp 跨域", "new": 0 } }, { "q": "jsonp post", "t": "n", "st": { "q": "jsonp post", "new": 0 } }, { "q": "jsonp callback", "t": "n", "st": { "q": "jsonp callback", "new": 0 } }, { "q": "jsonparser", "t": "n", "st": { "q": "jsonparser", "new": 0 } }, { "q": "jsonpath", "t": "n", "st": { "q": "jsonpath", "new": 0 } }, { "q": "jquery jsonp", "t": "n", "st": { "q": "jquery jsonp", "new": 0 } }, { "q": "jsonp jquery", "t": "n", "st": { "q": "jsonp jquery", "new": 0 } }, { "q": "jsonp 格式", "t": "n", "st": { "q": "jsonp 格式", "new": 0 } }, { "q": "jsonp原理", "t": "n", "st": { "q": "jsonp原理", "new": 0 } }], "s": ["json", "jsonp 跨域", "jsonp post", "jsonp callback", "jsonparser", "jsonpath", "jquery jsonp", "jsonp jquery", "jsonp 格式", "jsonp原理"] });