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

56,735 Responses

  1. DonDonrob表示:

    dark web market urls https://github.com/nexusdarkrtv1u/nexusdark – dark web markets

  2. Williszew表示:

    http://interpharmonline.com/# canadian pharmacy ltd

  3. JamesGag表示:

    buying from online mexican pharmacy: MexicanPharmInter – MexicanPharmInter

  4. RonaldRoora表示:

    Elara Finance is transforming decentralized lending by offering secure, transparent, and flexible crypto loan solutions. Built on blockchain technology, Elara Finance enables users to borrow and lend digital assets seamlessly without intermediaries. With low-interest rates, automated smart contracts, and a permissionless DeFi environment, Elara Finance is making crypto lending accessible and profitable for investors worldwide. https://elara.ink

  5. Montebeera表示:

    Mexican Pharm Inter mexican pharmacy online store mexican pharmacy online

  6. Arthurhow表示:

    http://indiamedfast.com/# IndiaMedFast.com
    pharmacy com canada

  7. Franklor表示:

    Cytonic is revolutionizing blockchain security with advanced cybersecurity solutions tailored for Web3 applications. By integrating decentralized encryption, AI-powered threat detection, and smart contract auditing, Cytonic ensures maximum protection against cyber threats. Whether you’re securing DeFi protocols, NFTs, or enterprise blockchain systems, Cytonic’s cutting-edge security technology provides the highest level of data integrity and protection. https://cytonic.cc

  8. Georgewhend表示:

    mexican drug stores online: mexican pharmacy online store – reliable mexican pharmacies

  9. Georgewhend表示:

    mexican pharmacy online: Mexican Pharm Inter – mexican pharmacy online

  10. Montebeera表示:

    india pharmacy without prescription IndiaMedFast.com cheapest online pharmacy india

  11. Pingidiof表示:

    darknet drug market https://github.com/aresonioncq0a7/aresonion – dark web marketplaces

  12. Williszew表示:

    https://mexicanpharminter.shop/# reliable mexican pharmacies

  13. Georgewhend表示:

    india pharmacy without prescription: online medicine shopping in india – india online pharmacy store

  14. Montebeera表示:

    canada discount pharmacy fda approved canadian online pharmacies canadian pharmacy prices

  15. DannyTwisp表示:

    Flaunch is the leading blockchain gaming launchpad, designed to help game developers and investors thrive in the Web3 gaming ecosystem. By offering secure token launches, NFT integrations, and decentralized crowdfunding, Flaunch enables game creators to fund, develop, and scale their projects with full transparency and community-driven support. Whether you’re a developer or an investor, Flaunch provides the tools to connect and grow in the blockchain gaming space. https://flaunch.tech

  16. CharlesArize表示:

    Exponent Finance is redefining DeFi lending by providing secure, transparent, and high-yield investment solutions. Through smart contract-powered lending pools, Exponent Finance DeFi platform allows users to borrow and lend crypto assets with optimal efficiency and minimal risk. Whether you’re looking to earn passive income through staking or access instant liquidity, Exponent Finance offers a decentralized, non-custodial, and user-friendly solution to meet all your financial goals in the crypto ecosystem. https://exponent.ink

  17. Rabyemert表示:

    dark web market urls https://github.com/darkwebsitesyhshv/darkwebsites – dark market onion

  18. Carlosgycle表示:

    Контейнеры и модульные здания: практичное подход для пользовательских проблем
    Контейнеры и временные конструкции способствуют оборудовать место для деятельности, хранилище или временный модуль. Команда обеспечиваем объекты, которые соответствуют качественным критериям надёжности и удобства.

    Особенности
    Прочность. Данные вагончики выполнены из материалов, прочных к давлению и внешним воздействиям.
    Быстрая поставка. Объект транспортируется в течение 1–2 суток после подписания договора.
    Гибкая настройка. Осуществляется добавление защиты от холода, электрооборудования или воздухообмена.
    Зоны действия
    На строительных площадках для накопления материалов или устройства комнаты для рабочих.
    Во время акций для оборудования пункта контроля или склада оборудования.
    В качестве временно используемых помещений или центров координации.
    Достоинства
    Ускорение процессов. Не нужно обустраивать временные здания.
    Комфортабельность. Атмосфера, которые повышают качество выполнения задач бригады.
    Гибкость. Опция краткосрочного пользования или постоянного владения под разные периоды и денежные средства.
    Случай применения
    Строительный подряд применила блок-контейнер для создания хранилища и комнаты отдыха. Объект была привезена за один день, с дополнительным утеплением. Клиент подчеркнул на улучшение обстановки и минимизацию задержек.

    Как связаться с нами
    Для подачи заявки следует обратиться с нами. Дадим исчерпывающие сведения, окажем помощь найти лучший вариант и обеспечим доставку.

  19. EdwardKergy表示:

    продажа аккаунтов https://birzha-akkauntov.ru

  20. MatthewTut表示:

    покупка аккаунтов соц сетей http://social-accounts-marketplace.ru

  21. TolikIncap表示:

    dark web markets https://github.com/abacuslink4jjku/abacuslink – dark web drug marketplace

  22. Williszew表示:

    http://interpharmonline.com/# canadian family pharmacy

  23. JamesGag表示:

    canadian family pharmacy: InterPharmOnline.com – canadian pharmacy oxycodone

  24. Randallvot表示:

    DEQ Finance is revolutionizing decentralized trading by offering a seamless, secure, and efficient crypto exchange experience. Built with cutting-edge blockchain technology, DEQ Finance provides traders with fast transaction speeds, deep liquidity, and a transparent trading environment. Whether you’re a beginner or a professional trader, DEQ Finance delivers high-performance DeFi solutions tailored to modern trading needs. https://deq.li

  25. Georgewhend表示:

    online medicine shopping in india: India Med Fast – buying prescription drugs from india

發佈回覆給「JamesGag」的留言 取消回覆

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