跳到主要內容

[分享] 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:為什麼 Junior 更快上手?Senior 要如何追趕?

現象層面(市場觀察) 最近有篇文章討論 junior & senior 開發者在 AI 時代的角色轉變,非常熱門。 身為 Cympack 產品開發團隊 ,我們也一直關注這個議題,在閱讀這篇文章時觀察到一些有趣的現象,對我們來說,這正好反映出 AI 正在改變開發生態,junior 借力 AI 快速成長、senior 則需要在 「架構思維」 與 「多 agent 協作」 中找到新定位,其中有些啟發(insight) 可以跟大家分享。 為什麼 Junior 更容易上手 vibe coding? 心智負擔低 → Junior 沒有太多傳統 code workflow 的框架包袱 敢於嘗鮮 → Gen Z / 年輕工程師天生習慣用 prompt-based 工具、跟 LLM 互動 少「優雅程式設計」的束縛 → 不太糾結「這樣寫會不會不夠優雅」,反而 embrace 快速迭代、快速出成果 反觀 Senior: 熟悉大型系統設計 有豐富的「工程正統流程」知識(架構設計、測試策略、效能優化、設計模式) 對 AI 生成 code 的品質 / 維護性通常比較保留 部分 10+ 年資深工程師,對 prompt engineering 沒那麼熟練,還在觀望 技能面(未來的關鍵能力) Vibe coding 本質上 = prompt engineering + AI co-pilot 管理能力 能力項目 誰目前比較有優勢? Prompt 撰寫 / AI 互動 Junior 較強(熟悉 chat-based 流程) 系統設計 / 架構把關 Senior 較強 AI 生成 code 驗證 / Bug 察覺能力 Senior 較強(能看出潛在問題) 快速疊代 / Hackathon 式開發 Junior 較強 長期維護性 / 穩定性 Senior 較強 總結 Junior 確實更快適應 vibe coding,並且更習慣以 「chat-based coding」 的工作流開發。 Senior 擁有驗證 AI 產物與系統設計的深度能力,但若不主動練習 vibe coding,長期會逐漸落後於新一波開發潮流。 就如同在 GAI 技術年會分享,希望帶給各位的感受, 『與 AI 協...

Vibe Coding 協作到自建 Dev Agent?從 Claude / Codex 到 OpenHands

過去一年,越來越多工程師開始 把 AI 真正帶進工作流程 。從一開始用 ChatGPT、Claude 來問語法問題,到後來很多人愛上 Cursor,直接在編輯器裡讓 AI 幫忙改 code、補 test case、甚至自動整理 PR。這樣的開發體驗,已經大大改變了我們寫程式的方式。 更現實的是,在很多企業內部、政府單位、或涉及機密資料的專案裡, 其實根本不能直接用 Cursor 或雲端 LLM 工具。   畢竟這些服務通常會把資料傳到雲端模型做處理,萬一專案裡有未公開的技術、敏感客戶資料,或是受限於法規 (像金融、醫療、政府標案) ,直接用雲端 AI 工具就會踩 紅線 。  因此,許多團隊反而更希望 「自己架一套 Dev Agent」 ,可以在內網執行,資料完全掌握在自己手上,該整合的內部工具、該讀的私有 repo、該串的 CI/CD pipeline,全部客製化、安全可控。 這時候,像 OpenHands 這樣的開源 Dev Agent 框架就特別有價值。它的出發點不是單純的 AI 助手,而是讓你能夠打造出一個真的可以跑在自己環境裡、可以理解整個開發流程的 AI 工程師。從建置到部署,從 CLI 操作到瀏覽器查詢, 從多檔案編輯到自動測試,全部都能自己完成,甚至還能針對不同專案調整專屬的工作流。 對很多開始探索 AI 協作開發的團隊來說,這是一條 從 「AI 幫你寫一段程式」,走向「AI 幫你解決一整個任務」 的進化路徑。而且,還是在可控、可自定義、安全的環境裡完成的。 🧩 主要概述 OpenHands 是由 All‑Hands AI 開發的開源「軟體開發代理人平台」,能模仿人類工程師從建立程式、修改程式碼、執行指令,到瀏覽網頁、呼叫 API……等一整套開發流程 它提供雲端(OpenHands Cloud)與本地 Docker 運行版本,用戶能配置 LLM(如 Claude、OpenAI、Gemini…) 📚 核心特性與怎麼使用 代理人的工具能力 支援代碼編輯、命令行、執行環境、網頁瀏覽、API 呼叫—接近人類開發者完整技能。其中 OpenHands Cloud 版本提供 $50 試用額度讓大家方便使用,又或者如果自己本機有 docker 的話,可以自己Local 版本透過 Docker 自架環境。 ...

Google Gemini 全端 AI Agent 快速入門 - 打造「思考」的 AI 助理

一套從搜尋、反思到輸出的全端 AI 代理人範例,讓你看懂什麼叫 Research Agent 在 AI 工具百家爭鳴的今天,大家都在問一個問題: 「我能不能不只問 AI 答案,而是讓它像一位助理一樣,有流程、有反思、還有出處,真正幫我完成一件事?」 Google 最近釋出了一個相當具有指標意義的開源專案 gemini-fullstack-langgraph-quickstart ,正是為了解這個問題而誕生。 這套系統到底是什麼? 這個範例不是傳統 Chatbot,而是展示一個完整的 AI research agent : 它會根據使用者的提問,自動發想搜尋關鍵字、查資料、整合重點,最後給出答案還附上引用來源。背後的邏輯設計得非常扎實,不只是能跑,更是具備可讀性、可擴展性與可商用性。 它的流程大致如下:  1. 使用者輸入問題(例如:「抖音是否影響台灣選舉?」)  2. Gemini LLM 幫你想出關鍵字(不只是照抄問題)  3. 呼叫 Google Search API 抓資料   4. LangGraph 控制流程 → 判斷資料夠不夠 → 若不足,自動補查  5. 整合最終答案,並產生 citation(來源說明) 你可以想像這就像一位實習助理幫你寫報告, 不只輸出一段內容,而是會 去查、會判斷、會補資料,而且說明「我為什麼這樣說」 。 LangGraph 是什麼角色? LangGraph 就是整個 Agent 背後的控制系統 。 用白話講,它幫你定義 AI 每一步要幹嘛、遇到什麼狀況該走哪條路、要不要反思、要不要再查,甚至可以定義條件邏輯與資料流動。 這就不像寫一個單純的 Chat API,而是比較像「把一個流程圖變成可以跑的程式」。 對工程師來說,它提供了從 prompt 到流程控制的設計彈性;對產品設計來說,它讓 AI 有了 「多步驟任務執行」 的能力。 技術架構與使用方式 這整套系統是 Fullstack 架構,前後端都幫你整好了,技術選型也非常實用:   前端:Vite + React + TailwindCSS + Shadcn UI  後端:FastAPI + LangGraph...