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>