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

42,887 Responses

  1. BrandonJer表示:

    п»їbest mexican online pharmacies mexico drug stores pharmacies medication from mexico pharmacy

  2. Haroldcox表示:

    Платформа 1вин предлагает широкий выбор спортивных событий, киберспорта и азартных игр. Пользователи получают высокие коэффициенты, быстрые выплаты и круглосуточную поддержку. Программа лояльности и бонусы делают игру выгоднее.

  3. Greta表示:

    Here is my web blog … Daycare Near Me – Find The Best Daycares
    Near You (Greta)

  4. Lt. Noah Robinson Lt.

  5. Feel free to visit my web-site … http://fwme.eu/

  6. There’s so much to think about, from discovering family-friendly lodging to selecting a vacation spot with activities that your entire crew will love.

  7. AgustinBougs表示:

    http://drugs24.pro/# cause of ed
    indian pharmacy paypal

  8. Geoffrey表示:

    Here is my blog; Geoffrey

  9. 오피表示:

    You’ve articulated something I’ve felt for a while.오피

  10. Gregorypurne表示:

    ed trial pack https://indianpharmdelivery.com/# online pharmacy india

  11. Gregorypurne表示:

    buy generic ed pills online http://indianpharmdelivery.com/# top 10 pharmacies in india

  12. BrandonJer表示:

    reputable indian pharmacies Online medicine home delivery indian pharmacies safe

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

  14. Профессиональный сервисный центр по ремонту сотовых телефонов в Москве.
    Мы предлагаем: ремонт ноутбуков выезд
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  15. Профессиональный сервисный центр ремонт сотовых телефонов рядом ремонты телефонов

  16. BrandonJer表示:

    best india pharmacy online shopping pharmacy india indian pharmacy

  17. RobertBex表示:

    музей анимации в москве измайлово московский музей анимации москва

  18. AgustinBougs表示:

    https://mexicanpharm24.pro/# buying prescription drugs in mexico online
    cheapest online pharmacy india

  19. Feel free to surf to my blog … Daycares By Category

  20. BrandonJer表示:

    top 10 online pharmacy in india world pharmacy india best india pharmacy

  21. Gregorypurne表示:

    buy prescription drugs online legally https://drugs24.pro/# best non prescription ed pills

  22. Hey there, You’ve done an incredible job. I?ll definitely digg it and individually recommend to my friends. I’m sure they’ll be benefited from this website.

  23. AgustinBougs表示:

    https://indianpharmdelivery.com/# india online pharmacy
    reputable indian pharmacies

  24. Experimente a emocao de Fortune tiger, um jogo cheio de sorte e premios incriveis esperando por voce!

  25. BrandonJer表示:

    errection problem cure mens erection pills cheap drugs

  26. I was pretty pleased to discover this website. I need to to thank you for ones time due to this wonderful read!! I definitely appreciated every part of it and I have you book marked to check out new things in your site.

  27. Hupetv表示:

    losartan 25mg ca – hyzaar drug buy generic keflex online

  28. AaronIdelt表示:

    7 simple secrets to eating the Mediterranean way
    kraken вход
    What if “diet” wasn’t a dirty word?

    During Suzy Karadsheh’s childhood in Port Said, Egypt, diet culture was nonexistent.

    “My parents emphasized joy at the table, rather than anything else,” Karadsheh said. “I grew up with Mediterranean lifestyle principles that celebrate eating with the seasons, eating mostly whole foods and above all else, sharing.”

    But when Karadsheh moved to the United States at age 16, she witnessed people doing detoxes or restricting certain food groups or ingredients. Surrounded by that narrative and an abundance of new foods in her college dining hall, she says she “gained the freshman 31 instead of the freshman 15.” When she returned home to Egypt that summer, “I eased back into eating the Mediterranean food that I grew up with. During the span of about two months, I shed all of that weight without thinking I was ever on a diet.”
    To help invite joy back to the table for others — and to keep her family’s culinary heritage alive for her two daughters (now 14 and 22) — Atlanta-based Karadsheh launched The Mediterranean Dish food blog 10 years ago. Quickly, her table started getting filled with more than just her friends and family.

    “I started receiving emails from folks whose doctors had prescribed the Mediterranean diet and were seeking approachable recipes,” Karadsheh said. The plant-based eating lifestyle, often rated the world’s best diet, can reduce the risk for diabetes, high cholesterol, dementia, memory loss and depression, according to research. What’s more, the meal plan has been linked to stronger bones, a healthier heart and longer life.

    Preparing meals the Mediterranean way, according to Karadsheh, can help you “eat well and live joyfully. To us, ‘diet’ doesn’t mean a list of ‘eat this’ and ‘don’t eat that.’” Instead of omission, Karadsheh focuses on abundance, asking herself, “what can I add to my life through this way of living? More whole foods, vegetables, grains, legumes? Naturally, when you add these good-for-you ingredients, you eat less of what’s not as health-promoting,” she told CNN.

發佈留言

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