2014年12月13日 星期六

JQuery讀取跨網域XML的方法

Javascript沒辦法直接跨網域存取資料。

可能要透過本地程式處理,或是透過第三方程式來處理。

常見的jQuery外掛,如:JGFeed

/*
* jGFeed 1.0 - Google Feed API abstraction plugin for jQuery
*
* Copyright (c) 2009 jQuery HowTo
*
* Licensed under the GPL license:
* http://www.gnu.org/licenses/gpl.html
*
* URL:
* http://jquery-howto.blogspot.com
*
* Author URL:
* http://me.boo.uz
*
*/
(function($){
$.extend({
jGFeed : function(url, fnk, num, key){
// Make sure url to get is defined
if(url == null) return false;
// Build Google Feed API URL
var gurl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q="+url;
if(num != null) gurl += "&num="+num;
if(key != null) gurl += "&key="+key;
// AJAX request the API
$.getJSON(gurl, function(data){
if(typeof fnk == 'function')
fnk.call(this, data.responseData.feed);
else
return false;
});
}
});
})(jQuery);
view raw jGfeed.js hosted with ❤ by GitHub

有趣的是,其實他還是透過google api去處理跨網域資料存取。

以下為測試範例:

<html>
<head>
<title>測試</title>
</head>
<body>
<div id='rss-styled'></div>
<script>
function showBlogData(data) {
$("#rss-styled").append('<ul>');
$.each(data.responseData.feed.entries, function(i, item) {
var htmlStr = '<li><a href="'+item.link+'">'+item.title+'</a> <span class="news-date">'+item.publishedDate+'</span><br>'+item.contentSnippet+'</li>';
$("#rss-styled").find('ul').append(htmlStr);
});
}
</script>
<script src="http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=showBlogData&q=http://edm.systemlead.com/syndication.axd">
</body>
</html>

沒有留言:

張貼留言