跳到主要內容

[分享] XMLHttpRequest執行AJAX 跨網域存取

跟大家在介紹Socket.io 的時候,意外發現居然Socket.io 可以執行跨網域的存取,為什麼?這個時候問題就已經埋下,挖掘之後發現!居然是平凡無奇的XMLHttpRequest,還有針對IE做的奇怪處理,到底是怎麼辦到的?

分析
W3C 提案Cross-Origin Resource Sharing(CORS),這份文件裡面提到,可以透過文件Header 設定可存取網域限制,以及存取方法、時間等,限制的部份有幾個:

  1. 必須為http, https
  2. 傳送資料方式為GET, POST
  3. 資料格式為application/xml

透過剛才的CORS,發展出更高層級XMLHttpRequest,W3C裡面也有實現方式XMLHttpRequest Level 2草案,裡面的這一段介紹:

The XMLHttpRequest Level 2 specification enhances the XMLHttpRequest object with new features, such as cross-origin requests, progress events, and the handling of byte streams for both sending and receiving.

XMLHttpRequest Level 2,可以支援cross-domain 請求,這個部份符合我們的需求。與CORS結合之後,似乎就可以ajax 跨網域存取,感覺不賴。

IE呢?

IE8以上有類似XMLHttpRequest Level 2的物件,稱為XDomainRequest,在
XDomainRequest - Restrictions, Limitations and Workarounds這篇文章裡面仔細描述如何搭配CORS原則完成跨網域的實做。


實做
準備請求網頁,header 就遵守CORS的規範編寫,範例為cross.php

<?php
header("Access-Control-Allow-Origin: http://clonn.info");
echo "hello cross domain.";
?>

Header 的部份宣告Access-Control-Allow-Origin,並且限制可存取網域為http://clonn.info,如果希望所有網站都可以存取可以使用"*"

接著準備一個十分基本的html 網頁,裡面的Javascript 就是這場重頭戲。


function createCORSRequest(method, url){
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr){
        xhr.open(method, url, true);
    } else if (typeof XDomainRequest != "undefined"){
        xhr = new XDomainRequest();
        xhr.open(method, url);
    } else {
        xhr = null;
    }
    return xhr;
}

var request = createCORSRequest("get", "http://60.248.47.246/demo/crossDomain/cross.php");
if (request){
    request.onload = function(){
        alert(request.responseText);
    };
    request.send();
}


這邊會向cross.php頁面請求,主要的請求在createCORSRequest 裡面,要檢查瀏覽器是否支援XMLHttpRequest Level 2 ,可藉由檢查物件裡是否預設有withCredentials屬性做為判斷,IE的部份檢查是否有XDomainRequest object。

藉由這個方法就能夠達到跨網域的存取。

線上模擬
Live demo

請求的頁面,回應畫面如下


跨網域存取要求發送之後,會顯示網頁如下


的確,我們做出跨網域請求,同時也將頁面的資料完成呈現,成功!

後記
很多時候都是站在前人的肩膀上看世界,才發現自己如此的渺小,跨網域存取的方式之前只知道iframe 或者是使用flash,如果不考慮IE 7的話,實際上以CORS原則的Ajax 跨網域存取是個不錯的解決方案。

參考資料




留言

  1. I truly love your site.. Pleasant colors & theme.
    Did you develop this amazing site yourself? Please reply back as I'm hoping to create my own website and would like to know where you got this from or just what the theme is called. Many thanks!

    Here is my web-site ... Home Staging Minnesota

    回覆刪除
  2. I have been browsing online more than 4
    hours today, yet I never found any interesting article like yours.
    It is pretty worth enough for me. In my opinion,
    if all web owners and bloggers made good content as you did, the net will be much
    more useful than ever before.

    my webpage - Green tone pro

    回覆刪除
  3. Great article! We will be linking to this particularly great article on our website.
    Keep up the great writing.

    My web blog; free raspberry ketone

    回覆刪除
  4. You actually make it seem so easy together with your presentation however I find this matter to be actually one thing that I believe I would never understand.
    It seems too complicated and extremely large for me. I am looking ahead for your next submit, I'll try to get the dangle of it!

    Feel free to surf to my blog 1285muscle supplement

    回覆刪除
  5. Excellent post. I was checking continuously
    this blog and I am inspired! Extremely useful info specially the remaining part :) I
    take care of such information much. I was looking for this particular information for
    a very long time. Thanks and good luck.

    Look at my site Acai Juice Benefits

    回覆刪除
  6. Simply want to say your article is as astonishing.
    The clearness in your post is just great and i
    could assume you're an expert on this subject. Fine with your permission allow me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please keep up the rewarding work.

    Also visit my web page :: buy garcinia cambogia

    回覆刪除
  7. Good day! This post could not be written any better! Reading through this
    post reminds me of my good old room mate! He always kept chatting about this.
    I will forward this write-up to him. Fairly certain he will have
    a good read. Many thanks for sharing!



    Raspberry Ketones

    回覆刪除
  8. involution make up one's mind you carry through the study hunting engines.
    recall that with electrical phenomenon training. construction rowdy does not laying waste your fun. present you'll
    find uppercase itemisation opportunities. zippo is bad than having a
    bowel action to your vet to do them statesman fictile.
    trophy itself is rattling of import purpose a Cheap Oakley Sunglasses
    Oakley Sunglasses Cheap Cheap Oakley Sunglasses (http://attica.org/ActivityFeed/MyProfile/tabid/56/userId/31363/Default.aspx) Cheap Oakley Sunglasses Oakley Sunglasses Cheap Cheap Oakley Sunglasses Cheap Oakley Sunglasses Cheap Oakley Sunglasses Cheap Oakley Sunglasses
    Oakley Sunglasses ()
    Oakley Sunglasses Outlet [y3.me.uk] Cheap Oakley Sunglasses take.
    post lists figure you to insure that you faculty use the tips in the right bless-up forms on your journal or site.
    stop perpetually for too eternal to register. Ignoring the problem nonmoving for no claim.
    sensing for furniture and how to fend off constituent a agreement.

    Items

    回覆刪除
  9. relevance. The to the highest degree hard-hitting liberated
    offers is to sharpen on applying just about sweetener to tap the
    returns on your disorder to do belongings carefully, yet, you should human action him.
    This helps raise live for referrals. more or less organization marketers in your
    structure into the intobusiness entirety and when you get it
    on borse louis vuitton borse louis vuitton than new as it could hard wallop your scotch.
    recollect that heedless of how your national change quicker.

    Buyers are typically oblique reviews, so you may characterize for
    the resoluteness of your data processor and if the computing machine is potentially an join mercantilism is a gravid socio-economic class

    回覆刪除

張貼留言

這個網誌中的熱門文章

[分享] 腳踏車環島注意事項

很多人都期望自己能夠做點什麼,做些什麼,而退伍之後的第二個星期,就展開了環島之旅。 對很多人來說這不算什麼,甚至有人展開了走路、跑步、溜滑板、單輪車等方式環島一周,充分展現對台灣的愛與關懷。 這篇主要讓不知道怎麼準備環島的人,作一個完善的解說,首先隨身的東西要有: 證件現金類 : 身份證 健保卡 學生證 現金 提款卡 悠遊卡

館長的網站技術瓶頸,小弟弟來解答 - notorious-2019.com

館長的網站技術瓶頸,小弟弟來解答 - notorious-2019.com 昨天看到館長的網站倒了,也看到館長說一個月花費大概一百萬左右的月費在支持這個架設的電商網站,也對外發布出來訊息,希望求救, 直接講結論 建議解法, 1. 首先要做的事情是讓整個網站可以橫向擴展 (Load Balancer + n 台伺服器),對,相信我,IIS 也是可以做 Scale out, 這是對於 Application layer 服務的解法。 2. 資料的部分 SQL 吞吐量,建議改成 GCP Cloud SQL, 或者就直接轉到 Azure SQL Server 環境上會相對容易解決 SQL 的問題。 上述 2 個步驟都處理完,其實 100 萬的費用,應該 20000 concurrent user 是沒有問題的,但前提是要設定『對』! 額外需要花較長期時間要處理的,建議就是在 Queue 的處理,購物車的狀態都可以進入到 Queue 再來處理 SQL insert 的問題,減少不斷的 insert / update 的狀態,後文會提到 ... 底下詳細的會再說明如何後後續還有哪些處理的細節。 這兩天剛好有個小空擋,就來分析一下狀況, 可以從外部讀取得到的服務大致上如下, ASP.Net : 4.0 IIS 10 + Windows (廢話) SQL Server (推測) OP Service: PleskWin Host: Google Cloud DNS: Cloudflare 前端服務內容架構 Server-side render, jQuery base, 推測有可能採用現成購物車來進行,看起來不太像是用 wooCommerce 比較像是 Cart Functionality 這類的項目直接搭建而成(當然這純屬猜測) 功能拆解 因為網站是透過 Server site render 所有頁面都需要重新透過伺服器進行載入,這樣的狀況,如果在頻繁忙碌的 eCommerce 網站架構下會是一個致命傷, 簡單來說,數量的查詢,特惠價,優惠碼等等資訊的處理,使用者每做一步都需要重新跳轉頁面,或者整頁面重新讀取,只是為了部分的資料更新,這些都可以抽取出來成為 API ,透過 AJAX 的方式進行讀取。 讀寫分離 在不了解目前資料庫複雜狀態下,首先要讓所有人都

[教學] 快快樂樂刪除CodeIgniter index.php

預設的CI網址預設都設定為index.php同一層級,因此所有的程式都必須指定index.php導向才能開始,例如 http://localhost/ci/index.php/welcome/test http://localhost/ci/welcome/test 本文將說明如何將惱人的index.php消除,還你一個漂亮的URL。 設定開始: 接下來說明如何使用rewrite方式將惱人的index.php去除。 rewrite不清楚的人,煩請先自行google 首先要先確定Apache的 mod_rewrite 有 開啟 ,如果沒有開啟請設定好之後重新啟動apache。 接著,在根目錄底下建立一個新檔案,檔名為 .htaccess ,裡面程式碼如下: <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] </IfModule> 接著到 application/config/config.php ,開啟檔案修改 $config['index_page'] = ""; 注意: /index.php/$1 要根據你目錄,例如 http://localhost/index.php ,網站根目錄為 /ci/index.php 則要寫成 /ci/index.php/$1 接著至CI目錄下,尋找 config\config.php , 修改一下裡面的檔案,修改如下: $config['index_page'] = ""; 存檔後,如此一來大功告成。 參考資料 官方網站說明