Ajax出现请求跨域错误问题,主要原因就是因为浏览器的“同源策略”,所谓同域是指,域名,协议,端口均相同,从一个网站访问其他网站的资源受到限制
CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。
1. JsonP方式解决跨域问题:(Jsonp 通常只是简单的get请求)
JSONP之所以能够用来解决跨域方案,主要是因为 <script> 脚本拥有跨域能力,而JSONP正是利用这一点来实现。具体原理如
C# mvc web api 后台:
public class JsonpResult<T> : ActionResult { public T Obj { get; set; } public string CallbackName { get; set; } public JsonpResult(T obj, string callback) { this.Obj = obj; this.CallbackName = callback; } public override void ExecuteResult(ControllerContext context) { var js = new System.Web.Script.Serialization.JavaScriptSerializer(); var jsonp = this.CallbackName + "(" + js.Serialize(this.Obj) + ")"; context.HttpContext.Response.ContentType = "application/json"; context.HttpContext.Response.Write(jsonp); } }
Controller 中的方法:
public ActionResult AjaxJsonp(string s, string f, string callback) { string result = s + '-' + f; return new JsonpResult<object>(new { result = result }, callback); }
前端Jquery 脚本:
$.ajax({ type: "GET", async: false, url: "http://localhost:63376/CommonActive/AjaxJsonp", dataType: "jsonp", jsonp: "callback", data: { s: '11', f: '22' }, jsonpCallback: "handler", success: function (result) { alert('success'); }, error: function (e) { var test = e; } });
2. CORS方案:
c# MVC 在webconfig中配置
"Access-Control-Allow-Headers":"X-Requested-With,Content-Type,Accept,Origin" <system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, Content-Type, Accept, X-Token" /> </customHeaders> </httpProtocol> </system.webServer>