標籤:style blog http io ar color 使用 sp for
前兩天碰到一個跨域問題的處理,使用jsonp可以解決。(http://www.cnblogs.com/xtechnet/p/4123210.html)
最近再整理了一下:
1.jsonp。
ajax請求,dataType為jsonp。這種形式需要請求在服務端調整為返回callback([json-object])的形式。如果服務端返回的是普通json對象。那麼調試的時候,在chrome瀏覽器的控制台會報"Uncaught SyntaxError: Unexpected token"錯誤;在firefox瀏覽器的控制台會報"SyntaxError: missing ; before statement"錯誤。
2.iframe跨域。
頁面中增加一個iframe元素,在需要調用get請求的時候,將iframe的src設定為get請求的url即可發起get請求的調用。
var url = "http://xxx.xxx.xxx?p1=1&p2=2";$("#iframe").attr("src", url);//跨域,使用iframe
iframe方式強於jsonp,除了可以處理http請求,還能夠跨域實現js調用。
3.script元素的src屬性處理
iframe、img、style、script等元素的src屬性可以直接向不同域請求資源,jsonp正是利用script標籤跨域請求資源的簡單實現,所以這個和jsonp本質一樣,同樣需要服務端請求返回callback...形式。
var url="http://xxx.xxx.xxx?p1=1";var script = document.createElement(‘script‘);script.setAttribute(‘src‘, url);document.getElementsByTagName(‘head‘)[0].appendChild(script);
4.在伺服器使用get處理。
對於業務上沒有硬性要求在前端處理的,可以在服務端做一次封裝,再服務端發起調用,這樣就可以解決跨域的問題。然後再根據請求是發出就完,還是需要擷取傳回值,來決定代碼使用同步或者非同步模式。
private static void CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } var request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; if (!string.IsNullOrEmpty(userAgent)) { request.UserAgent = userAgent; } if (timeout.HasValue) { request.Timeout = timeout.Value; } if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } request.BeginGetResponse(null,null);//非同步 //return request.GetResponse() as HttpWebResponse; }
5.flash跨越
過於尖端了==,再研究
參考:
http://www.cnblogs.com/think/archive/2010/06/23/1763616.html
http://www.jb51.net/article/42472.htm
http://www.jb51.net/article/29180.htm
js跨域問題(2)