Parsing XML / RSS from URL using Java Script

前端 未结 3 989
栀梦
栀梦 2020-12-08 08:00

Hi i want to parse xml/rss from a live url like http://rss.news.yahoo.com/rss/entertainment using pure Java Script(not jquery). I have googled a lot. Nothing worked for me.

3条回答
  •  没有蜡笔的小新
    2020-12-08 08:32

    One big problem you might run into is that generally, you cannot get data cross domain. This is big issue with most rss feeds.

    The common way to deal with loading data in javascript cross domain is calls JSONP. Basically, this means that the data you are retrieving is wrapped in a javascript callback function. You load the url with a script tag, and you define the function in your code. So when the script loads, it executes the function and passes the data to it as an argument.

    The problem with most xml/rss feeds is that services that only provide xml tend not to provide JSONP wrapping capability.

    Before you go any farther, check to see if your data source provides a json format and JSONP functionality. That will make this a lot easier.

    Now, if your data source doesn't provide json and jsonp functionality, you have to get creative.

    On relatively easy way to handle this is to use a proxy server. Your proxy runs somewhere under your control, and acts as a middleman to get your data. The server loads your xml, and then your javascript does the requests to it instead. If the proxy server runs on the same domain name then you can just use standard xhr(ajax) requests and you don't have to worry about cross-domain stuff.

    Alternatively, your proxy server can wrap the data in a jsonp callback and you can use the method mentioned above.

    If you are using jQuery, then xhr and jsonp requests are built-in methods and so make doing the coding very easy. Other common js libraries should also support these. If you are coding all of this from scratch, its a little more work but not terribly difficult.

    Now, once you get your data hopefully its just json. Then there's no parsing needed.

    However, if you end up having to stick with an xml/rss version, and if you're jQuery, you can simply use jQuery.parseXML http://api.jquery.com/jQuery.parseXML/.

提交回复
热议问题