透過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...

41,762 Responses

  1. Hey there, I think your website might be having browser compatibility issues. When I look at your blog site in Safari, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, excellent blog!

  2. I couldn’t resist commenting. Perfectly written!

  3. tilifoun.com表示:

    My webpage: Daycare Near Me – Find The Best Daycares Near
    You (tilifoun.com)

  4. lee jae won表示:

    Heya! I just wanted to ask if you ever have any trouble with hackers? My last blog (wordpress) was hacked and I ended up losing a few months of hard work due to no back up. Do you have any solutions to prevent hackers?

  5. Great post. I am going through many of these issues as well..

  6. Williebak表示:

    Я не могу молчать о той несправедливости, которая обрушилась на нас и наш кооператив «Бест Вей». Этот кооператив был создан для нас, для военнослужащих и наших семей, чтобы мы могли жить в достойных условиях. Мы доверили ему наши сбережения, надеясь на честность и порядочность. И что мы имеем в итоге? Наши деньги арестованы, наши квартиры заблокированы, а нас заставляют бегать по судам и писать бесконечные заявления. Наши мужья, сыновья и братья рискуют жизнями на фронте, а в тылу их права грубо нарушаются. Это не просто несправедливость, это настоящее предательство со стороны тех, кто должен защищать закон. Колокольцевская мафия, как я теперь ее называю, своими действиями разрушает жизни тысяч семей. Ветеран Вооруженных сил, 83-летний Виктор Иванович Василенко, отец Романа Василенко, оказался на скамье подсудимых – это просто извращение. Мы не можем и не будем молчать. Я надеюсь, что министр обороны Андрей Белоусов и президент Владимир Путин обратят внимание на этот беспредел и вернут нам наши права.

  7. I do accept as true with all the ideas you have introduced on your post. They’re really convincing and will definitely work. Still, the posts are very short for novices. Could you please lengthen them a little from next time? Thank you for the post.

  8. Harris表示:

    Feel free to visit my blog … Harris

  9. Find high-quality fashion at lucky brand store.

  10. This blog was… how do you say it? Relevant!! Finally I’ve found something which helped me. Many thanks!

  11. Feel free to surf to my web page: Poker Online Free

  12. I do not even know how I ended up here, but I thought this post was great. I do not know who you are but certainly you’re going to a famous blogger if you aren’t already 😉 Cheers!

  13. Sv132表示:

    Oh my goodness! Amazing article dude! Many thanks, However I am going through problems with your RSS. I don’t know the reason why I am unable to subscribe to it. Is there anybody having the same RSS problems? Anybody who knows the answer will you kindly respond? Thanks.

  14. Having read this I thought it was rather informative. I appreciate you finding the time and energy to put this informative article together. I once again find myself personally spending way too much time both reading and leaving comments. But so what, it was still worthwhile!

  15. ElliotRep表示:

    Джип туры по Крыму https://м-драйв.рф/tours/uvidet-vsyo-za-odin-den/ уникальные маршруты и яркие эмоции. Погрузитесь в увлекательнее приключение вместе с нами. Горные, лесные, подземные экскурсии, джиппинг в Крыму с максимальным комфортом.

  16. bad medical表示:

    Very good info. Lucky me I came across your blog by accident (stumbleupon). I have saved it for later!

  17. Pretty! This has been a really wonderful article. Thanks for providing this info.

  18. Jamesric表示:

    tamoxifen depression: buy tamoxifen online – aromatase inhibitors tamoxifen

  19. DanielTet表示:

    buy cytotec in usa https://lisinopril.guru/# prinivil 5mg tablet
    furosemida 40 mg

  20. Dino Game 28表示:

    After I initially commented I appear to have clicked on the -Notify me when new comments are added- checkbox and now each time a comment is added I get four emails with the same comment. Is there a means you are able to remove me from that service? Thanks.

  21. Jamesric表示:

    cytotec buy online usa: cytotec best price – Misoprostol 200 mg buy online

  22. After looking over a few of the articles on your web page, I truly appreciate your technique of blogging. I book-marked it to my bookmark site list and will be checking back in the near future. Please visit my website too and let me know how you feel.

  23. Jamesric表示:

    lisinopril 5 mg tablet cost: buy lisinopril – lisinopril 5 mg tablet cost

  24. DanielTet表示:

    Abortion pills online https://furosemide.win/# lasix pills
    lasix dosage

發佈留言

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