跳到主要內容

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

    回覆刪除

張貼留言

這個網誌中的熱門文章

RAG 和 Prompt 原理超簡單解說!想知道 AI 怎麼找答案看這篇

這篇文章是給對於你已經開始使用所謂的 ChatGPT / Claude / Gemini 之類的 AI 服務,甚至是 Siri (嘿丟,他也是一種 AI 應用服務喔) 簡單來說是非 技術人員, PM,小白,想要趕快惡補的人 ,直接花十分鐘可以看完的一篇科普業配文章。 或者是概念僅止於,AI 這東西會幻想,會有誤差,會對於生活有些幫助但沒有幫助的人們,做個簡單又不是太簡單的介紹,希望用一個非常入門的方式讓你們有個了解。 當然,這篇文章目的很簡單, 就是引流 ,如果你身邊有已經對於 Web 技術開發的人員,歡迎報名分享給他,年末出國不如學一技在身,參加今年我們舉辦最後一場 RAG 實作工作坊,報名連結 , https://exma.kktix.cc/events/ai-for-dev-course-rag-2 注意: 接下來每個大段落結束都會有一段工商導入,但文章絕對精彩,請注意! 為了讓各位容易想像,我們將整個世界的資訊,先濃縮到這本『西遊記』的世界觀當中,我們整個世界都在這個 『西遊記』 ,而 大型語言模型 我們用 『書精靈』 來描述。 PS. 我們先預設各位,應該都有聽過,西遊記!如果沒有聽過西遊記的,請右轉出去,謝謝! 先來談談向量 在《西遊記》的世界裡,我們可以把 向量想像成一種「內容座標」 ,讓系統知道每個角色、場景、法術等的 「位置」和「距離」 。向量幫助語言模型知道不同內容之間的關聯程度。 向量就像內容的「距離」和「位置」 比方說,唐三藏的 「位置」(向量)會接近「佛經」和「取經」 的概念,因為他一路上都是為了取經而前進。孫悟空的 向量位置則會更靠近「金箍棒」和「七十二變」 這些概念,因為這些是他的特徵。 相似內容靠得更近:像「佛經」和「取經」會靠近唐三藏的向量,因為它們彼此有很強的關聯。 相差較大內容會離得較遠:像「取經」和「妖怪」「妖怪的寶藏」就距離比較遠,因為妖怪的寶藏和取經的目標關聯性不大。 是誰決定的這些位置? 簡單來說,這些位置和關係是模型自己學出來的。語言模型會閱讀大量的資料和這世界觀的資訊,觀察哪些詞語經常一起出現,根據「共同出現的頻率」來決定它們的關係,並且自動生成向量。例如: 如果模型看到 「唐三藏」 總是和 「取經」 一起出現,它就會讓「唐三藏」的向量靠近「取經」。 ...

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 協...

v0 API 是什麼?怎麼用?一篇教你搞懂功能、價格,還能搭配 Cursor 玩出 vibe coding!

Vercel 的 v0 是一款 AI 驅動的前端開發工具,能夠將自然語言描述轉換為可部署的 React 元件和 UI 介面,支援 Tailwind CSS,並可直接部署至 Vercel 平台。此外,v0 提供 API 介面,讓開發者能將其整合至其他工具,如 Cursor IDE,進一步提升開發效率。 Vercel v0 API 介紹 v0 API 目前處於 Beta 階段,主要提供 v0-1.0-md 模型,具備以下特點: 多模態支援:接受文字與圖片(base64 編碼)輸入。  快速串流回應:提供低延遲的串流回應。  OpenAI 相容:遵循 OpenAI Chat Completions API 格式,易於整合至現有工具。  前端開發優化:特別針對 Next.js 和 Vercel 等現代前端框架進行優化。 要使用 v0 API,需訂閱 Premium 或 Team 方案 ,並啟用使用量計費。 使用方式 API 端點: POST https://api.v0.dev/v1/chat/completions 請求標頭: Authorization: Bearer YOUR_V0_API_KEY Content-Type: application/json 參數範例: { "model": "v0-1.0-md", "messages": [ { "role": "user", "content": "建立一個具有身份驗證功能的 Next.js AI 聊天機器人" } ], "stream": true } 您也可以使用官方的 AI SDK 進行整合: npm install ai @ai-sdk/vercel 範例程式 javascript import { generateText } from 'ai'; import { vercel } from '@ai-sdk/vercel'; const { text } = await generateText({ model: vercel...