js跨域請求資料的3種常用的方法

來源:互聯網
上載者:User

標籤:tle   jquer   請求   --   data   sync   ready   stat   .net   

由於js同源策略的影響,當在某一網域名稱下請求其他網域名稱,或者同一網域名稱,不同連接埠下的url時,就會變成不被允許的跨域請求。
那這個時候通常怎麼解決呢,對此菜鳥光頭我稍作了整理:
1.JavaScript
   在原生js(沒有jQuery和ajax支援)的情況下,通常用戶端代碼是這樣的(我假設是在localhost:8080的連接埠下的http://localhost:8080/webs/i.mediapower.mobi/wutao/index.html頁面的body標籤下面加入以下代碼):

<script>  var xhr = new XMLHttpRequest();  xhr.open("get", "http://i2.mediapower.mobi/adpower/vm/Bora/js/test.js", true);  xhr.onreadystatechange = function() {    if (xhr.readyState == 4 && xhr.status == 200) {      console.log(xhr.responseText);    }  };  xhr.send(null);</script>

儲存,瀏覽器開啟http://localhost:8080/webs/i.mediapower.mobi/wutao/index.html,並且開啟console控制台:

 

瀏覽器很無情的給你彈出一個同源限制的錯誤,意思就是你無法跨域請求url的資料。
那麼,我先採取第一種策略,運用html中的script標籤,插入js指令碼:
(1)通過script標籤引用,寫死你需要的src的url地址,比如:

<script>var callbackfunction = function(data) {  console.log(‘我是跨域請求來的資料-->‘ + data.name);};</script><script src="http://i2.mediapower.mobi/adpower/vm/Bora/js/test.js?callback=callbackfunction"></script> 

這裡我定義一個callbackfunction的函數,然後用script標籤的src屬性跨域請求資料,那麼,test.js的內容經過約定,需要寫成這樣:
callbackfunction({"name":"wwwwwwwwwwww"});
儲存,開啟index.html並重新整理:

 

(2)你也可以動態加入script標籤,讓html解析的時候,動態載入script指令碼,並請求遠端資料:

<script>var callbackfunction = function(data) {  console.log(‘我是跨域請求來的資料-->‘ + data.name);};var script = document.createElement(‘script‘),  body = document.getElementsByTagName(‘body‘);script.src = ‘http://i2.mediapower.mobi/adpower/vm/Bora/js/test.js?callback=callbackfunction‘;body[0].appendChild(script);</script>

結果和上面一樣。

 

2.jQuery中的$.ajax()

   設想,當你想要使用jQuery請求跨域資料的時候,比如(還是剛才的index.html):

<script src="js/jquery-1.11.3.js"></script><script>$(function(){  $.get(‘http://i2.mediapower.mobi/adpower/vm/Bora/js/test.js‘,function(data){    console.log(data);  })})</script>

瀏覽器還是無情的報錯,因為你這個url是不同的網域名稱下的。

那麼既然jQuery封裝了ajax方法,我們為何不用,人家封裝好了,你不用,豈不是找罪受麼,代碼如下:

<script src="js/jquery-1.11.3.js"></script><script>$(function(){  $.ajax({    async: false,    type: "GET",    dataType: ‘jsonp‘,    jsonp: ‘callback‘,    jsonpCallback: ‘callbackfunction‘,    url: "http://i2.mediapower.mobi/adpower/vm/Bora/js/test.js",    data: "",    timeout: 3000,    contentType: "application/json;utf-8",    success: function(msg) {      console.log(msg);    }  });})</script>

 

當你作了這麼多挑逗工作之後,瀏覽器很爽快的給出了反應,表示它很爽,返回給了你一個對象,裡面是遠端不同網域名稱下test.js中的資料。
3.postMessage+iframe

   postMessage是HTML5中新增加的功能,比如我在本地區名下,http://192.168.1.152:8080/webs/i.mediapower.mobi/wutao/testa.html中的testa.html中:

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>testa</title></head><script>window.onload = function() {  document.getElementById(‘ifr‘).contentWindow.postMessage(‘我是要經過傳遞的資料‘, ‘http://i2.mediapower.mobi/adpower/vm/Bora/testb.html‘);};</script><body>  <iframe id="ifr" src="http://i2.mediapower.mobi/adpower/vm/Bora/testb.html"></iframe></body></html>

此時,我遠端的testb.html裡面的內容應該是這樣:

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>testb</title></head><script>window.addEventListener(‘message‘, function(event) {  // 通過origin屬性判斷訊息來源地址  if (event.origin === ‘http://192.168.1.152:8080‘) {    alert(event.data);   }}, false);</script><body>123</body></html>

儲存代碼,開啟本地testa.html,訪問遠端的testb.html

 

總結了一下,jQuery還是非常的好用的,基本上js能乾的事情,jQuery都能非常快速並且高效的完成,當然,原生js也能解決很多事情,而HTML5的新功能也非常強大,這幾種方法,我還是首推jQuery。

以上就是為大家分享的3種常用的js跨域請求資料的方法,希望對大家的學習有所協助。

 

-->點擊查看原文<--

js跨域請求資料的3種常用的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.