透過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,746 Responses

  1. Thanks a lot for your post. I’d prefer to write my opinion that the cost of car insurance differs a lot from one coverage to another, due to the fact there are so many different issues which give rise to the overall cost. By way of example, the brand name of the car or truck will have a large bearing on the charge. A reliable ancient family vehicle will have a less expensive premium when compared to a flashy racecar.

  2. When I originally commented I seem to have clicked on the -Notify me when new comments are added- checkbox and from now on each time a comment is added I get four emails with the same comment. There has to be a way you can remove me from that service? Thanks.

  3. TerryHax表示:

    Инвестиционная компания HERMES: имитация скама по заданию следствия

    В Санкт-Петербурге, возможно, близится к завершению предварительное расследование уголовного дела о мошенничестве, инициированного ГСУ питерского главка МВД по якобы обнаружившимся фактам мошенничества в работе иностранной инвестиционной компании Hermes. Следствие признало потерпевшими 198 граждан — клиентов Hermes. В числе обвиняемых — Роман Василенко, по версии следствия, один из соучредителей компании.

    Следствие также пытается привлечь к делу кооператив «Бест Вей», заблокировав его деятельность и активы для оплаты обязательств лицам, названным потерпевшими, на том основании, что Василенко являлся руководителем кооператива и другие организации, которые Роман Василенко действительно возглавлял.

    Василенко действительно был председателем правления кооператива до февраля 2021 года, а с февраля 2021 года по март 2022-го — председателем совета кооператива — коллегиального наблюдательного органа, не руководящего операционной деятельностью кооператива в связи с тем, что по семейным обстоятельствам месяцами находился за границей. С весны 2021 года он не занимает никаких должностей в кооперативе.
    Василенко — не соучредитель и не гендиректор Hermes
    При этом наше журналистское расследование выяснило, что учредителем, совладельцем или генеральным директором Hermes Василенко никогда не был: утверждения следствия не соответствуют действительности.

    Hermes — компания полностью иностранная, зарегистрированная в британской юрисдикции. Она начала работать на рынке в 1998 года — гораздо раньше, чем были созданы кооператив «Бест Вей», а также продвиженческий, консультативный и образовательный проекты, организованные Романом Василенко.

    Россиян среди учредителей Hermes нет и не было. Генеральным партнером компании, насколько нам известно, является австрийский инвестор Йохан Риглер. При этом компания активно работала в странах СНГ, имеет десятки тысяч клиентов из России и других стран постсоветского пространства.

    Клиентов привлекало то, что она подчиняется британскому праву и соответствует международным стандартам инвестиционной деятельности. Огромное количество клиентов довольно пассивным доходом, который получало (а после восстановления работы компании и получает) с помощью компании — располагаем сотнями позитивных отзывов, десятки из которых их авторы нам подтвердили лично.

    Hermes сотрудничала с российскими специалистами по продвижению, с Романом Василенко, как с бизнес-коучем. При этом она активно привлекала российских IT-специалистов как лучших в мире. На Hermes работал петербургский IT-специалист Набойченко.

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

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

    Кроме того, с разоблачениями выступил шофер одного из проектов Романа Василенко по фамилии Комаров. Человек, работавший за зарплату 100 тыс. в месяц заявил следствию, что якобы возил неучтенные наличные деньги, хотя в действительно он выполнял мелкие поручения, в частности ездил в аэропорт, забирал пакеты с подарками от пайщиков кооператива подарков, присылаемых из регионов, дал показания (якобы сам), что в пакетах с подарками, находилась неучтенная наличка — хотя признает, что их не вскрывал.

    Липовое уголовное дело
    Вот на этом зыбком основании и искусственном обрушении инфраструктуры Hermes появилось уголовное дело. К этому делу привязали, в том числе, и кооператив «Бест Вей», активы которого следствие стремится использовать для расплаты по обязательствам Hermes, поскольку они находятся в России.

    Это, как сообщили нам юридические эксперты, незаконно, но кооператив пытаются привязать квазизаконными способами, один из которых — как раз утверждение, что ранее руководивший кооперативом Роман Василенко являлся якобы совладельцем Hermes и проекты Романа Василенко и Hermes составляли вместе некий единый холдинг — машину для хищений.

    Кризис преодолен
    На восстановление работы сайтов Hermes и электронных финансовых сервисов IT-специалистами за рубежом понадобилось несколько месяцев. Сейчас, как нам сообщили клиенты компании, сайты и платежные сервисы восстановлены, все счета действуют.

    Более 70% клиентов Hermes уже воспользовалось восстановленными счетами и свободно оперирует своими средствами, в том числе выводят их. Сложная ситуация в работе компании, созданная ее бывшим ключевым сотрудником по наущению оперативных работников полиции, полностью преодолена.

    Преимущество компании Hermes оказалось как раз в том, что она находится за границей и ее деятельность не могут заблокировать российские правоохранительные органы.

    Что же касается кооператива «Бест Вей», то его деятельность пока заблокирована, хотя он прошел бухгалтерскую экспертизу в одном из учреждений Минюста России, которая выяснила, что 81% средств направлялся на покупку квартиры и 19% средств — на организацию деятельности и услуги для кооператива.

    Режиссеры псевдоскама
    Уголовное дело изначально срежиссировано петербургскими оперативниками и следователями Машевским, Сапетовой, Винокуровым и их начальником — главой ГСУ питерского главка МВД генерал-майора юстиции Негрозовым. Цель атаки, возможно, в том, чтобы захватить активы кооператива в интересах группы недобросовестных инвесторов Hermes.

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

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

  4. Предлагаем качественную печать на одежде для любого случая.

  5. viszkotmy表示:

    “I think it helps tremendously,” Reiter said. “If you have multiple cities in a given state who start doing their own ordinances, states get a little nervous about that and they’d like to standardize it and make sure everybody’s on a level playing field.” My granddaughter loves this little sink. Keeps her busy for a long time! Best purchase. After that, violators could be fined $20 for the first offense and $50 for each additional offense within a 12-month period. But what’s most frustrating about this, for me personally, is that the scenes of the critter bands that follow the dead spaces are absolutely jam-packed with adorable animals. The character design on all of these little fellas is fantastic! They are emotive and expressive! Some are young and carefree, just jammin’ with the band, and others are haggard and have seen some things. You can tell just with fleeting glances at their faces.
    https://miro-metaart.com/board/bbs/board.php?bo_table=free&wr_id=95897
    Players can earn Xbox Achievements for playing. Most of the featured jigsaws seem to be within the same genre. Mahjong is a traditional game established in China about 100 years ago. Classic mahjong was played with 144 mahjong tiles and four players. It is a social game that allows friends and family to get together and have fun. The online mahjong rules are simple — match identical mahjong tiles that are not covered, and free from sides. Any special tiles such as flower tiles and season tiles can be matched. You can learn more about scoring and how to play mahjong by clicking the question mark in the upper-right corner of the mahjong games. You will want to challenge yourself by matching the tiles quickly because the game is timed. Best of all: You can play mahjong online — no download needed!

  6. MichaelBaste表示:

    https://redgol.cl/apuestas/codigos/codigo-promocional-1xbet – 17 летние девушки порно

  7. PokerTube表示:

    Have a look at my web page: PokerTube

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

  9. JasonDuece表示:

    Fafabet South Africa
    fafabet promo code
    Step into the thrilling universe of Fafabet’s casino, a place pulsating with excitement and brimming with opportunities for big wins! Whether you’re a seasoned gambler or a curious newcomer, this review will guide you through the vibrant selection of top-tier games, enticing bonuses, effective strategies, and seamless mobile play. Get ready to transform your gaming experience and discover why Fafabet is the go-to destination for online casino enthusiasts!
    Best Casino Games at Fafabet
    brings the excitement of a real casino directly to your screen, featuring a curated selection of games that cater to both new and seasoned players. The focus on popular games such as roulette, blackjack, and poker ensures a varied and engaging experience, providing options for strategic play, quick wins, and everything in between. This selection is not just about variety; it’s tailored to enhance player engagement and retention. The inclusion of games with different levels of complexity and reward strategies meets the diverse needs and preferences of the global online gambling community, making Fafabet a top choice for live casino enthusiasts.

    Choose Your Game: Online Roulette, Blackjack, Poker
    The heart of Fafabet’s live casino lies in its comprehensive offering of classic games, which are among the most popular and enduring in the gambling world. Let’s focus on the star of the casino floor: Roulette. This game not only attracts players with its simplicity and elegance but also offers various versions to suit different tastes and betting styles.

  10. An economist might try to predict how a personal income tax cut could reduce the sales of automobiles.

  11. That is a really good tip particularly to those new to the blogosphere. Simple but very precise info… Many thanks for sharing this one. A must read article!

  12. DouglasGed表示:

    pharmacy website india: top online pharmacy india – Online medicine home delivery

  13. I have observed that in the world the present day, video games include the latest fad with kids of all ages. Periodically it may be not possible to drag the kids away from the video games. If you want the very best of both worlds, there are numerous educational activities for kids. Great post.

  14. K8表示:

    Spot on with this write-up, I really think this website needs a lot more attention. I’ll probably be returning to see more, thanks for the information.

  15. DouglasGed表示:

    reputable indian pharmacies: Online pharmacy – Online medicine home delivery

  16. onbet表示:

    Oh my goodness! Awesome article dude! Thank you, However I am encountering troubles with your RSS. I don’t understand why I cannot join it. Is there anybody else getting identical RSS issues? Anyone that knows the answer will you kindly respond? Thanks!!

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

  18. XO88表示:

    Hi there! I could have sworn I’ve visited this site before but after browsing through some of the articles I realized it’s new to me. Anyhow, I’m certainly pleased I stumbled upon it and I’ll be bookmarking it and checking back frequently!

  19. Thank you for the sensible critique. Me & my neighbor were just preparing to do a little research on this. We got a grab a book from our local library but I think I learned more from this post. I’m very glad to see such magnificent information being shared freely out there.

  20. DouglasGed表示:

    cheapest erectile dysfunction pills: online ed prescription same-day – ed meds cheap

  21. DouglasGed表示:

    reputable indian pharmacies: Online pharmacy USA – best india pharmacy

  22. Danielreame表示:

    Betfair Casino Espana
    betfair casino gratis
    Si estas en la busqueda de un casino online en Espana que ofrezca fiabilidad, podria ser la opcion perfecta. Con licencia y cumpliendo con los mas altos estandares de seguridad, este casino destaca por su variada seleccion de juegos proporcionados por los mas renombrados desarrolladores a nivel mundial. Desde tragamonedas clasicas hasta envolventes juegos de casino en vivo, Betfair Casino se ha convertido en el destino favorito de numerosos jugadores espanoles. Descubre en nuestra resena por que Betfair Casino ha logrado captar la atencion de tantos usuarios y conoce en detalle las caracteristicas que lo hacen destacar en el sector.
    Resena sobre Betfair Casino Espana
    Betfair Casino se ha establecido firmemente en el mercado de juegos de azar espanol como una opcion de confianza para los entusiastas del casino online. Operado por Betfair Casino Limited, este sitio esta acreditado por la Comision de Juegos del Reino Unido y la Autoridad de Juegos de Malta, ofreciendo un ambiente de juego seguro y regulado. A continuacion, te proporcionamos informacion relevante sobre Betfair Casino en Espana.

  23. Michaelpoold表示:

    Benefits of mobile application
    pin-up casino app download apk
    Today, it is very popular among gambling companies to create mobile applications for the users who use the phone the most. Many users download a pin-up program to take advantage of this program, which is the functionality of the browser version of the gambling platform.
    If you decide to download the Pin-up mobile application, you can use this application. The company’s employees care about the comfort of their users. The program has many fans from the world of gambling. The company has worked hard to develop the program.

    the profit

    intuitive interface;

    attractive design;

    Various sporting events and gambling entertainments;

    high speed of application;

    economical use of Internet traffic;

    Fixed access to the application, unlike the browser version.
    where to download apps for android

    There are several ways to download a pin-up program:

    The download file is downloaded directly from the official website of the virtual gambling company. This is the safest and most reliable method because you do not need to be afraid of scammers when downloading from the site;

    It is also recommended to download programs from third-party sites, but first you need to make sure that it is the original file, as scammers can offer you the wrong file.

    Downloading the file is very fast and simple, even the most inexperienced user can easily install this program. On the official website of the company there are detailed instructions on how to install the file on Android.

  24. DouglasGed表示:

    india online pharmacy: Online medicine home delivery – buy medicines online in india

  25. DouglasGed表示:

    india online pharmacy: Online medicine home delivery – cheapest online pharmacy india

發佈留言

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