跳到主要內容

[分享] 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.0IIS 10 + Windows (廢話)SQL Server (推測)OP Service: PleskWinHost: Google CloudDNS: Cloudflare前端服務內容架構Server-side render, jQuery base, 推測有可能採用現成購物車來進行,看起來不太像是用 wooCommerce 比較像是 Cart Functionality 這類的項目直接搭建而成(當然這純屬猜測)功能拆解因為網站是透過 Server site render 所有頁面都需要重新透過伺服器進行載入,這樣的狀況,如果在頻繁忙碌的 eCommerce 網站架構下會是一個致命傷,簡單來說,數量的查詢,特惠價,優惠碼等等資訊的處理,使用者每做一步都需要重新跳轉頁面,或者整頁面重新讀取,只是為了部分的資料更新,這些都可以抽取出來成為 API ,透過 AJAX 的方式進行讀取。讀寫分離在不了解目前資料庫複雜狀態下,首先要讓所有人都可以讀取到資料,頁面可以跑出來,建議至少將讀取資料庫,和寫入資料庫的…

Scrum management tool 敏捷開發工具概觀介紹

Scrum management 工具概觀介紹
會有這個念頭興起主要也是因為這幾個月內,是在公司內部訓練透過 Teddy 老師 Scrum 課程了解整個 Scrum 的流程,開始進行團隊的 Scrum 流程導入。

在過年春節期間去嘗試市面上的 Scrum 管理軟體,也透過眾多大大得到解答

這邊就不詳細討論怎麼進行 Scrum 的軟體開發,而是在於管理機制,就整個流程上,對於自己需要的項目有,
SprintUser Story (Backlog)Task management task time countertask assigneeburndown chart 以上這幾個是在 Scrum 流程裡面最基本的需求以及解法,而根據大量搜尋結果,也找到許多不同平台,以下為個人分析經驗,
trello.comhttps://trello.com/ 一開始很直覺的就會採用到 Trello ,而經過測試後,如果直接的使用 trello 是沒有辦法達到以上的所有方法,必須要結合,scrum for trello ,所以也表示如果你的電腦沒有安裝 Chrome的話,勢必就是 GG
的確這是一個假命題,身為一個開發者,或者前端人員怎麼可能沒有 Chrome ,(也許真的沒有),不過比較麻煩的是,雖然 trello 加上套件後可以管理 Task, time counter, burndown chart 都有支援,但是通常一個 Sprint 會有兩到三個 User Story ,所以對於 task 橫向管理對應 User Story 是比較麻煩的。
taiga.iohttps://taiga.io/ Taiga 也是許多人推薦的一套管理系統,就整體表現以及流程上,的確沒有像是 trello 這麼順暢,不過從另外一個方面來看,他是完全 open source ,而且可以 self host 這點來說,的確是非常適合用於自己的敏捷專案管理上,這點的確可以說是開源軟體的轟炸機。

不過就回到 Scrum 管理層面來說,畢竟人家 taiga 開宗明義就說了,流程上是符合于 kanban ,所以缺少了 task time counter 的部份,也沒有 User story 管理。所以回到 Scrum 本身,Taiga 就並不是這麼適合。
blossom.iohttps://www.blo…