透過JS跨網域存取XML檔

為了一些安全性的因素,通常伺服器會阻擋跨網域的XML存取,當然如果你是該網站開發者,所開發的頁面應該將會被放在被認可的網域中,不會碰到這個問題,但我們在開發前期有可能會不在所屬的網域,這樣就會造成開發上的困難,不過我們可以透過Yahoo所提供的YQL查詢語法來解決這個問題,以下就是相關的說明:

若我們在自己的電腦用以下的語法去存取一個網路上的XML

<script>
    $(function () {
        var xmlSource = "http://stanley.cloudlab.tw/crossDomainXML/testXML.xml";
        $.ajax({
            url: xmlSource,
            success: function (data) {
                console.log(data);
            }
        })
    })
</script>

很可能會出現「No Access Control Allow Origin」的訊息:

Cross doamin XML access

但如果套用上YQL之後

<script>
$(function(){
	var xmlSource = "http://stanley.cloudlab.tw/crossDomainXML/testXML.xml";
	var yqlURL = [
		"http://query.yahooapis.com/v1/public/yql",
		"?q=" + encodeURIComponent("select * from xml where url='" + xmlSource + "'"),
		"&format=xml&callback=?"
	].join("");

	$.getJSON(yqlURL, function(data){
		console.log(data)
	});
	
})
</script>
Cross doamin XML access

可以看到已經可以抓到XML內容,這樣可以讓我們較為方便的去開發,其他詳細的使用說明可以參考Yahoo YQL Guide

You may also like...

40,385 Responses

  1. RobertSoish表示:

    buy ciprofloxacin over the counter: ciprofloxacin generic price – buy cipro without rx

  2. washi tape表示:

    You should be a part of a contest for one of the finest websites on the net. I will recommend this site!

  3. link bokep表示:

    After I originally commented I appear to have clicked on the -Notify me when new comments are added- checkbox and now every time a comment is added I recieve 4 emails with the same comment. There has to be an easy method you can remove me from that service? Thanks a lot.

  4. ngentot表示:

    I would like to thank you for the efforts you have put in penning this website. I’m hoping to check out the same high-grade content from you in the future as well. In truth, your creative writing abilities has inspired me to get my very own blog now 😉

  5. Отличный сайт! Всем рекомендую!бумажные пакеты

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。