AJAX跨域問題總結

來源:互聯網
上載者:User

標籤:ext   等等   tty   bsp   ring   listen   style   javascrip   跨域訪問   

跨域是什嗎?

首先說下同源,同源策略是瀏覽器的一種安全性原則,所謂同源是指,網域名稱,協議,連接埠完全相同。而跨域就是不同源 !

能夠進行跨域的請求

一般a,img,link[rel=stylesheet],video,audio,等等能夠發出請求的標籤都可以實現跨域訪問。但是這些標籤不能得到返回的東西,所以一般不會用他們來請求資源。

常見的跨域處理方案:

由於ajax先天設計的時候,不能實現跨域訪問。所以就出現了處理跨域這樣的問題。 
① jsonp來處理跨域,下面用jQuery來實現,關鍵代碼如下:

$.ajax({  type : "GET",  url : "http://www.a.com/index.php?message=msg&callback=?",  dataType : "jsonp",  jsonp: ‘callback‘,  success : function(json){ console.log(json.msg); }});

② 服務端設定 Access-Control-Allow-Origin 
我們使用nodejs來完成這一問題。服務端代碼如下:

"use strict"const http = require(‘http‘);const server = http.createServer();server.on(‘request‘,(req,res)=>{ res.writeHead(200,{"Content-Type":"text/plain","Access-Control-Allow-Origin":"*"}); res.write(‘ajax cross domain‘); res.end();})server.listen(3000,(err)=>{ if(err){ return console.log(err.message); } console.log(‘server is on‘);})

瀏覽器端代碼如下:

window.onload = function(){  var xhr = new XMLHttpRequest(); xhr.open("post","http://localhost:3000/"); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status==200){ console.log(xhr.responseText); } } } xhr.send(null);}

使用http的形式訪問用戶端網頁,那麼就會輸出不同源下返回的資料。 
③ 其他跨域策略 iframe, window.postMessage()等 
詳見: http://rickgray.me/2015/09/03/solutions-to-cross-domain-in-browser.html

④ 使用豆瓣的api,簡單封裝一個跨域請求函數:

<script>    /* 封裝資料  跨域url  params fn */    function crossDomain(url,params,fn){ var head = document.getElementsByTagName(‘head‘)[0]; // 1. 處理回呼函數 var cbName = ‘jsonp‘+ (Math.random() * Math.random()).toString().substr(2) + new Date().getTime(); /* 將回呼函數掛載到window對象上 */ window[cbName] = function(data){ // 拿到並處理資料 fn(data); // 拿到資料後remove掉 //head.removeChild(scriptObj); } // 2. 解析url var qstring = ‘‘; for(var key in params){ qstring += key + ‘=‘ + params[‘key‘] + ‘&‘; } qstring += ‘callback=‘ + cbName; url += ‘?‘ + qstring; // 3. 插入script var scriptObj = document.createElement(‘script‘); scriptObj.src = url; head.appendChild(scriptObj); }</script><script> /* 使用 */ crossDomain(‘http://api.douban.com/v2/movie/in_theaters‘,{},function(data){ console.log(data); })</script>

AJAX跨域問題總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.