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

  1. IgnacioSlima表示:

    pharmacie en ligne france livraison belgique: Pharmacie Internationale en ligne – pharmacie en ligne fiable

  2. Allenacurf表示:

    п»їpharmacie en ligne france: levitra generique prix en pharmacie – trouver un mГ©dicament en pharmacie

  3. Allenacurf表示:

    vente de mГ©dicament en ligne: kamagra oral jelly – Achat mГ©dicament en ligne fiable

  4. Eu recomendo o melhor cassino Tigrinho

  5. Experimente este melhor cassino Tigrinho

  6. Allenacurf表示:

    Pharmacie sans ordonnance: pharmacie en ligne sans ordonnance – pharmacie en ligne sans ordonnance

  7. Отличный сайт! Рекомендую заглянуть тудаСтроительный консалтинг в Москве

  8. IgnacioSlima表示:

    Achat mГ©dicament en ligne fiable: pharmacie en ligne pas cher – п»їpharmacie en ligne france

  9. Allenacurf表示:

    pharmacie en ligne france pas cher: Cialis sans ordonnance 24h – pharmacie en ligne france livraison internationale

  10. Allenacurf表示:

    Prix du Viagra 100mg en France: Acheter du Viagra sans ordonnance – Viagra pas cher paris

  11. Allenacurf表示:

    acheter mГ©dicament en ligne sans ordonnance: acheter kamagra site fiable – pharmacie en ligne france livraison internationale

  12. IgnacioSlima表示:

    Viagra en france livraison rapide: viagra en ligne – Viagra gГ©nГ©rique sans ordonnance en pharmacie

  13. Allenacurf表示:

    pharmacie en ligne france fiable: pharmacie en ligne – pharmacie en ligne france fiable

  14. Allenacurf表示:

    pharmacies en ligne certifiГ©es: pharmacie en ligne pas cher – Pharmacie sans ordonnance

  15. IgnacioSlima表示:

    Pharmacie en ligne livraison Europe: kamagra 100mg prix – pharmacie en ligne livraison europe

  16. EdwardGROOM表示:

    pharmacie en ligne france livraison belgique: Acheter Cialis 20 mg pas cher – pharmacie en ligne fiable

  17. RobertBlica表示:

    https://levitraenligne.shop/# pharmacies en ligne certifiées

  18. Vksiwy表示:

    claritin pills lie – claritin pace claritin pills trace

  19. Allenacurf表示:

    pharmacie en ligne france fiable: pharmacie en ligne pas cher – vente de mГ©dicament en ligne

  20. IgnacioSlima表示:

    pharmacie en ligne: levitra generique – pharmacie en ligne pas cher

  21. RobertBlica表示:

    https://cenligne.com/# pharmacie en ligne france

  22. Allenacurf表示:

    pharmacie en ligne pas cher: acheter kamagra site fiable – Pharmacie Internationale en ligne

  23. Allenacurf表示:

    pharmacie en ligne france fiable: Acheter Cialis – pharmacie en ligne avec ordonnance

  24. JseraldAposy表示:

    Купить Диплом Бакалавра Цена
    Можно воочию убедиться, что наши бакалавры института неотличимы от официальных. Каждому приходится учиться, сначала в школе, потом в училище, техникуме или университете. Весь дипломный проект отправляется в электронном виде на указанный вами емейл. В этой цене услуг есть немало мошенников всех мастей, готовых обмануть наивных клиентов. Купить высшее образование в России: путь к быстрой карьере и уважению. Мы предлагаем изготовить точную копию диплома или любого образовательного документа – такую, что ни один специалист не сможет распознать в ней подделку. Хоть ты досконально знаешь нюансы специальности, но, как говорится: Без бумажки человек букашка.
    http://https://arusak-diploms-srednee.ru
    Договор Купли Продажи Доли В Квартире
    Обучение в университете проходит в очной или заочной форме, а также дистанционно. Довериться нам стоит даже в том случае, когда оригинальный документ (если тот вообще существовал) был выдан много лет назад и даже в другой стране. Мы обеспечиваем высокую степень правдоподобности документа, готового выдержать проверку. Твердый переплет выполняется несколькими способами: термосклеивание.
    Генеральная Доверенность Спб Цена
    Купленный бакалавр Цена будет куплен Диплом по индивидуальному заказу с учётом личных пожеланий и заверен требуемым количеством печатей и подлинных подписей. После подтверждения макета заказ отправляется по указанному адресу. Обращаясь к нам, будьте уверены, что каждое пожелание будет услышано. Обратившись в нашу компанию, вы сможете купить высококачественный диплом в Кирове на бланке ГОЗНАК по приемлемой цене.

  25. DavdidApari表示:

    Купить Диплом Вуза С Реестром
    Купить диплом МИЭТ – или любого ВУЗа России. Купить диплом МИЭМ – или любого ВУЗа России. Купить диплом МИЭП – или любого ВУЗа России. Купить диплом МГЮА – или любого ВУЗа России. Купить диплом МГАУ – или любого ВУЗа России. Купить диплом МИРБИС – или любого ВУЗа России.
    russkiy365-diploms-srednee.ru
    Lbgkjv
    Здесь вы можете приобрести настоящие дипломы со всеми атрибутами подлинности. Купить диплом в Глазове у нас – это получить высококлассный документ по честной цене Купить диплом о высшем образовании в Барнауле с нашей компанией можно очень быстро и просто. Вас приятно удивят наши цены, обращайтесь. Качество и сервис гарантируем.
    Доверенность На Постановку На Учет Автомобиля Бланк
    На нашем сайте вы можете легко подобрать документ под ваш бюджет, поскольку вариантов выбора тут предостаточно. Обратившись в нашу компанию, Вы можете быть уверены в качестве всех предоставляемых бланков и в наличие всех степеней защиты. Ваш документ будет содержать знаки защиты от копирования, что позволит ему проходить проверку на приборах с ультрафиолетовым свечением.

  26. Usata表示:

    Data via MLB Odds at Vegas-Odds MLB betting is increasing in popularity and a one-stop shop for daily MLB odds is an invaluable tool for MLB bettprs. With 30 teams playing 162 regular-season MLB games per season, there are more opportunities to bet on baseball than in any other major American sport. Not all offers available in all states. Please gamble responsibly. If you or someone you know has developed a gambling problem or addiction, contact 1-800-GAMBLER. Sports Data APIs To stay competitive with other top online betting sites, PointsBet also features daily and weekly MLB promotions for existing users as well. During the MLB season, be sure to look for bonuses catered to MLB lines and odds. These could include odds boosts and even MLB parlay insurance.
    https://aphorismsgalore.com/users/clovfallectw
    This platform’s commitment to customer satisfaction is evident through its responsive 24 7 support and robust affiliate program. It allows users to earn rewards while enjoying the thrill of gaming. Yes, you can download and install the Babu88 mobile app on the official website for Android and iOS smartphones. I found the babu88 app handy because I was able to switch to Bengali in it right away. I quickly registered and started betting on it, and so far everything goes without problems. Babu88 I’ve been using the Babu88 app for about 3 months now. I haven’t found any technical issues. The only issue is that sometimes you have to download an update. Do not create multiple emails with the same question. Wait for a reply from the Babu88 support team and communicate in one thread of letters. Also remember the norms of cultural communication. Be polite no matter what happens.

  27. RobertBlica表示:

    https://levitraenligne.com/# pharmacie en ligne france livraison internationale

  28. Allenacurf表示:

    п»їpharmacie en ligne france: trouver un mГ©dicament en pharmacie – pharmacie en ligne sans ordonnance

  29. IgnacioSlima表示:

    Viagra femme ou trouver: viagra sans ordonnance – Sildenafil teva 100 mg sans ordonnance

  30. Usata表示:

    Predictions are received in telegram because there is very rarely a problem with the delivery of notifications and everything is the fastest, and as you know in betting, speed is the most important. Scotland – Lowland League Poland – Division 2 Tomorrow – 17:15 Scotland – Lowland League Scotland – Lowland League Scotland – Lowland League Scotland – Lowland League We recommend that you play each bet in this section on a single slip, ie as a single. This depends mostly on your bank, because if you play with smaller amounts it is better to combine them to get higher odds, but if your bets are in the range of €50 or €100, then the single game is much safer. Tomorrow – 17:15 Poland – Division 2 Tomorrow – 17:15 Scotland – Lowland League We recommend that you play each bet in this section on a single slip, ie as a single. This depends mostly on your bank, because if you play with smaller amounts it is better to combine them to get higher odds, but if your bets are in the range of €50 or €100, then the single game is much safer.
    https://wiki-stock.win/index.php?title=Sure_wins_tomorrow_matches_0549
    At Tipsfame,we are the world best prediction site, we provide soccer predictions soccer tips and in-depth analysis for more than 50 leagues (both major leagues – Premier League Predictions, Serie A Predictions, La Liga Predictions, Predictions La Liga Bundesliga, French Ligue 1 Predictions, etc. Minor leagues – English Championship, Serie B, Segunda League and many more.) compete around the world. However we are the best free soccer prediction website, if you want to become a successful bettor, you need the right betting advice and information. From 50 odds, 10 odds, 3 odds, 2 odds, single bet, over 1.5, over 2.5, double chance to mention a few winning predictions, Tipsfame will help you predict Guess soccer matches correctly. If you are looking for accurate soccer predictions for free , Tipsfame is the best football prediction site.

發佈留言

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