跳到主要內容

[分享] 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

    回覆刪除

張貼留言

這個網誌中的熱門文章

Vibe Coding:到底?氛圍驅動程式開發必殺技?

Vibe Coding(氛圍編程) 是由 OpenAI 共同創辦人 Andrej Karpathy 在 2025 年提出的革命性程式開發方式,它讓開發者透過自然語言與 AI 對話來生成程式碼,徹底改變了傳統的編程模式。 這種開發方式的核心理念是 「順著感覺走」 ,讓 AI 處理技術細節,開發者專注於創意和需求描述。 Vibe Coding 需要基本上的規劃和執行,但並沒有強制規範,從日常經驗來說可分為三個階段, 前期準備、開發過程、和後期維護 三個關鍵階段。每個階段都有其特定的任務和注意事項,正確執行這些步驟將大幅提升開發效率和程式品質。 將靈感與需求透過 AI 快速轉化成產品功能或原型。以下幫你分成 「前、中、後」 三階段要做的事情,適合你自己做、或帶團隊做 前期:設定 vibe & 準備素材 這個階段的重點是 「建立開發語境」 ,因為 AI 的生成表現高度依賴前期提供的上下文與資料。 明確目標 :釐清要解決的問題、預期要做的功能與核心價值。例如在筆記軟體的情境中,可能是:「我要做一款讓使用者能用 Markdown 記錄筆記,並提供標籤與全文搜尋功能的簡單 App。」 收集靈感 :觀察同類產品(如 Obsidian、Notion)、蒐集市場痛點(例如太多筆記軟體無法脫機使用,或同步效能差)。 建立語境 :準備初步 prompt、背景知識、產品定位、品牌調性、目標使用者輪廓等。 確認資源 :決定用哪些工具(Gemini、ChatGPT、設計軟體、流程管理工具等)。 確認完上述內容之後,就可以先開始進行準備規格,進行第一次的 Vibe Coding 方向驗證 提示詞模板準備 很多人會跳過這步驟,但一份 「好的 AI 提示詞模板」 將決定接下來每一次 AI 對話的品質。有效的提示詞模板需具備: 描述具體且無歧義 包含技術要求和約束條件 提供範例資料和測試案例 指定程式碼風格和慣例 例如針對筆記軟體的案例:   「建立一個支援 AI 功能純文字筆記,輸入內容可即時渲染;需支援儲存到本地檔案,提供標籤欄位做分類;以 React 架構,程式風格採用 Tailwind style components 並使用 hooks。」 開發工具選擇 開發工具的選擇 同樣重要,目前市場上主要的 ...

Claude Code Hooks:自動化與安全的最佳實踐

寫在最前頭,這份文章主要寫起來是給自己看, 同時內容是比較適合開發者,工程師們可以做些自動化處理的簡單筆記。 Claude Code hooks Claude Code hooks 是一種強大的自動化機制,允許用戶在 Claude Code 的不同生命週期階段,自定義執行 shell 指令。這種設計讓開發者能夠將規則和自動化行為嵌入到應用層級,確保每次都能可靠執行,而不必依賴 LLM(大型語言模型)是否會選擇執行某項操作。 Hooks 的核心用途 通知 :自訂收到 Claude Code 等待用戶輸入或執行權限時的提醒方式。 自動格式化 :如在每次檔案編輯後自動執行 prettier (針對 .ts 檔)、 gofmt (針對 .go 檔)等。 日誌記錄 :追蹤所有執行過的命令,便於合規或除錯。 自動反饋 :當 Claude Code 產生不符合團隊規範的程式碼時,自動給出反饋。 自訂權限 :阻擋對生產環境檔案或敏感目錄的修改[^1]。 配置與結構 Hooks 透過設定檔進行配置,分為全域( ~/.claude/settings.json )、專案( .claude/settings.json )、本地專案( .claude/settings.local.json )以及企業級策略設定。每個 hook 由「事件名稱」和「匹配器」組成: "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "jq -r '...'" } ] } ] } matcher :用於匹配工具名稱(支援正則表達式),如 Write 、 Edit|Write 、 Notebook.* 。 hooks :當匹配時要執行的命令陣列。 type :目前僅支援 "command" 。 ...

[CSS] z-index 在不同瀏覽器繼承問題

今天會討論到這個課題,是因為要實做一個Popup dialog,所以我們希望的結果如下圖。 可是在IE7 卻發生了這樣的情況。 Popup不論怎麼設定z-index都無法浮在最上層,我們看一下html架構發生什麼事情。