跳到主要內容

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

    回覆刪除

張貼留言

這個網誌中的熱門文章

面試者如何挑戰大工程師時代來臨?

面試者如何挑戰大工程師時代來臨? 全世界都在倡導轉職成為工程師,似乎轉職成為工程師就成為職場的救贖,真的是如此嗎?讓老衲來杠給各位聽。 最近有位好久不見的小朋友,是 2000 年出生的小蔡,對於即將面臨到面對職場的挑戰開始關心起技術,他開始尋找比較適合自己的領域,同時也開始在思考到底為了接下來的就職小蔡該如何準備。 詢問我說是不是可以考慮軟體開發工程師這條路線 對於他的詢問,反而引起我的注意, 這讓我開始思考並映射於最近招募的經驗,軟體開發此領域是不是對於每個人都是可以擔任的職啀,這邊分享一些自己的看法希望對各位有所幫助。 全民工程師這件事情 在全球景氣低迷的狀況下,的確特別在這一年大家會很有感覺萬物齊漲,薪水不漲,薪資就是一直停滯不前。 很多時候,在不同的領域中,會發現整個薪資就算是擔任了管理職務主管你也會面臨到薪資的強大屏障在自己面前。 這個時候, 軟體工程師年薪百萬口號 似乎就成了一種救贖。 好像成為了工程師就可以達到年薪百萬,在家輕鬆工作,不用打卡也不用受到風吹雨淋,隨時想工作就可以工作,每個月又有固定薪水入帳,感受到類財富自由,人生的美好。 如果能夠爭取到跨國公司的職位,這份薪水有可能還可以上看每個月十多萬以上,甚至是往上也是極度有可能的事情,人生美好層次又再度提高了起來。 但這件事情是真的每個人都可以達到嗎? 還是這就是另外一種性存者偏差呢? 亦或者這些人其實是金字塔頂端的小眾? 每份履歷都像是同一種履歷 最近在最近幾年在面試工程師的時候特別會看到許多轉職者,一開始履歷裡面看到相關的作品一開始會覺得十分的驚艷, Wow, 現在的新手就可以做到如此精美的畫面,這些畫面是我當初用 Bootstrap 也做不出來的東西,許多的互動體驗好的一個不行,做出來的頁面配色和對齊也是極致。 但是隨著時間推移,多看了幾封履歷之後,就會發現在各大技術養成學院出來的學生履歷成果內容如出一轍,在面試的過程中也會詢問許多關於框架的底層概念,和比較技術觀念的時候,甚至是許多框架的核心概念,就很容易露出馬腳。 很多面試者會 一問三不知 ,透過許多引導,但殘酷的是連關鍵字是什麼都也無法推敲出來,更不用說在小組裡面到底怎麼樣合作,許多不同線上產品的比較,使用者流程,使用者後面的互動邏輯等,幾乎是風吹一片倒,只能

jQuery, animate function with css exlapenation.

Today, I want to use jQuery making a animation for webpage, First I check animate fuction on ref book. I clearly know how use it, there are two main function for animate. 1. $().animate({ "style1":"value1" , "style2":"value2" }, Time); Time: it can be three type, String => "slow", "fast", "normal". Integer=>10000 2. $().stop(); it can immedaitely stop animation. Let's do some experieces, I bulit a simple page. You can hover UP and DOWN for a article sliding UP or DOWN. Les't do it. HTML CODE: <div id="all"> <div id="up">往上</div> <div id="showTab"> <div id="data"> About This script is intended for forms where the user needs to upload an image to a Web site. The image is displayed on the page for previewing before uploading. The display will be resized if needed so as not to break the page layout. Valid file types are set in the scri

初級工程師的迷霧:解析開發中常見的困擾與挑戰

在我和工程團隊的共事歷程中,我注意到初級工程師經常遇到的問題。這些問題,無論在面對簡單或複雜的挑戰時,都能體現出來。歸納起來會有常見以下幾個面向。 簡單的問題 發現許多初級工程師在面臨簡單或複雜的問題時,常有可能會遇到困難,時常會有一種繞圈圈的氛圍, 常見問題分別有, 問題本質 首先是對於問題本質上並沒有釐清完成的目標,以及問題本身是要解決什麼樣的商業問題,客戶問題,導致於因為總總原因,做了 scope 過大,或者,花了過多時間進行 over design 的問題發生。 過度依賴套件 發現在新手開發中,會發現為了解決單一問題,卻引用了一大包的 libary 或者引用了不適合此問題的套件。在求解的過程中,容易導致要解決套件的問題,而忘記了要解決的問題是什麼。 複雜的問題 我們在面對複雜的問題時,經常會因為缺乏策略與經驗而感到困惑,反而在處理看似簡單的問題時,卻可能因為過度依賴套件或缺乏組合技巧,而陷入泥淖。不論是複雜或是簡單的問題,我們都需要找到更有效的解決方式。 不論是經常過度依賴套件求解,又或者複雜的問題不知道如何拆解。因此導致新手可能會感到無所適從,不知道如何運用組合技巧。因此,他們往往在處理看似簡單的問題時,容易陷入困境,導致專案的時程延宕。 特別是各自工程師都有開發壓力時,身為新手開發者就更難與資深開發者進行討論,從中汲取前輩的經驗,轉化成自身的價值發生。 解決的方向 上述的問題,自己再開發的時候也或多或少會發生,當然在新入門者更是容易深陷其中,不知如何自拔。 除了參與社群,從傾聽到互動的過程中,從前輩的經驗進行思考及內化的過程。 在 AI Generated 時代,我們可以透過 LLM 透過適當的思考方式和問答過程,逐步的逼近答案,也許是一條可以進行的道路。 這裡,會以透過內部訓練的經驗,提出如何以 ChatGPT 這樣的工具為例,提升對於新手工程師的幫助。 透過 ChatGPT,我們可以解決許多類似的問題。例如,我們可以透過 ChatGPT 建立一個問答系統,進行問題分析,或是請 ChatGPT 提出最適合的工具和方法來解決問題,尤其是那些可以透過使用基礎 function 就能處理的簡單問題。這不僅能讓我們避免過度依賴套件,更能發掘並利用基礎工具的能力。 工商時間 7/3 (週