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

46,529 Responses

  1. Dennisscalp表示:

    https://withoutdoctorprescription.xyz/# pain medications without a prescription

  2. ShooraBor表示:

    clomid fertility We ll cover what safely stopping TRT should look like in just a minute.

  3. ShooraBor表示:

    Lupron is cleared from the body relatively quickly so the ovaries are not hyper stimulated. clomid pct dosage Based on the current evidence, the American Society for Reproductive Medicine doesn t recognize luteal phase defect as a specific cause of infertility.

  4. Josephcoume表示:

    molnupiravir pills molnupiravir brand name

  5. ShooraBor表示:

    Jerry Sebag – he has pioneered a partial vitrectomy for floaters which avoids cataract formation. buy clomid australian dollars live birth or detrimental e.

  6. MatthewSycle表示:

    https://viagracanada.xyz/# viagra online no prior prescription

  7. Andreprark表示:

    https://withoutdoctorprescription.xyz/# cvs prescription prices without insurance

  8. Duane表示:

    I have been surfing online more than 2 hours today, yet I never found any interesting article like yours.
    It’s pretty worth enough for me. In my opinion, if all site owners and bloggers made good content as you did,
    the net will be a lot more useful than ever before.

  9. preerse表示:

    OPKs didn t work well for me b c I got the peak fertility days multiple times a month b c of the PCOS and my BBTs were all over the place. clomid side effects men In fact, most athletes consume anabolic steroids on a trial and error approach based on information gained from other athletes, coaches, websites, or gym gurus.

  10. It’s very trouble-free to find out any matter on net as compared to books, as I found this article at this web site.

  11. hello there and thank you for your information – I have certainly picked up anything new from right
    here. I did however expertise some technical points using this web
    site, since I experienced to reload the website lots of times previous to I
    could get it to load correctly. I had been wondering if your web host is OK?
    Not that I’m complaining, but sluggish loading instances times will often affect your placement in google and could damage your high-quality
    score if advertising and marketing with Adwords.
    Anyway I am adding this RSS to my email and can look out for much more of your respective interesting content.
    Make sure you update this again very soon.

  12. Redracc.com表示:

    You made some really good points there. I looked on the internet for additional information about the
    issue and found most people will go along with your views on this site.

  13. Talloupisn表示:

    gay web chat rooms
    bbc gay chat room free
    gay chat rooms no registration

  14. Dennisscalp表示:

    https://molnupiravir.life/# molnupiravir covid price

  15. Talloupisn表示:

    free gay mens chat phone
    little gay boys who want to sex chat with men
    shemale/gay online chat sites

  16. ThekPhend表示:

    2012; 19 97 103. clomid bodybuilding Failed to call in prescriptions to pharmacy.

  17. MatthewSycle表示:

    https://paxlovid.best/# covid pills treatment

  18. Josephcoume表示:

    nolvadex gynecomastia nolvadex online

  19. MatthewSycle表示:

    https://tamoxifen.best/# nolvadex online

  20. Htvjnd表示:

    zithromax online prednisolone 40mg cost prednisolone 40mg drug

  21. Whgzxh表示:

    azithromycin 500mg brand buy azithromycin 250mg generic prednisolone 5mg oral

  22. Blanca表示:

    Right now it seems like Drupal is the best blogging platform out there right now.
    (from what I’ve read) Is that what you’re using on your blog?

  23. Kennethrop表示:

    Быстрые займы и микрозаймы онлайн https://dostupno48.ru
    в МФК, срочная выдача на банковскую или кредитную карту, предоставление заема высоким % одобрения и выдача заемщику займа буквально за несколько минут с помощью сервиса МФО, возврат легко и удобно на на сайте по интернету, низкая процентная ставка и любые способы получения денежной суммы: онлайн, наличными в офисе МФО, перевод на банковский счет, перевод на банковскую или кредитную карту. Плюсы и типы займов: без отказа, на короткий срок, круглосуточные, по договору с финансовой компанией, без проверки КИ, с просрочками. МКК предлагают хорошие условия кредитования для постоянных занимателей и при повторных займах. Подберите микрозайм, заполните заявку на заём. Лучшие займы и ТОП потребительских займов от кредиторов.

  24. Uzkoyw表示:

    azithromycin online buy generic neurontin cost prednisolone 20mg

  25. Talloupisn表示:

    gay chat rooms ring central
    shemale/gay online chat sites
    gay cumshot chat

  26. Andreprark表示:

    https://viagracanada.xyz/# do you need a prescription for female viagra

  27. Josephcoume表示:

    molnupiravir generic name molnupiravir kaufen preis

  28. Dennisscalp表示:

    https://viagracanada.xyz/# what drugs should not be taken with viagra?

發佈留言

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