2011-12-29 82 views
0

我想解析一个XML feed,然后抓取一个特定的ID和其中的内容。我需要这样做只与JS ...加载XML获取特定ID的内容jQuery或Javascript

我已经尝试过各种方式,没有运气。我得到的最接近的是:

var html = $("#dangericon").html(); 
$("#test").append(html); 

但是,当我尝试首先加载xml时,这不适用于我。它必须是在页面...看到:http://jsfiddle.net/BZDBF/5/

我曾尝试: 阿贾克斯,.load,也.parseXML(),但是,不工作,由于格式不正确的XML ...

我的xml链接是:http://www.sierraavalanchecenter.org/bottomline-rss.php 我想获取#dangericon内容,即图像。

谢谢大家。

+0

你想用小提琴演奏什么? XML在哪里? – 2011-12-29 19:47:01

+1

您通常无法通过Javascript加载XML(例如,通过$ .ajax()),除非该提要在您的域中。不过,您可以在服务器上加载并解析它。你没有访问服务器端编码吗? – 2011-12-29 19:49:53

+0

“...由于格式不正确的XML而无法正常工作” - 是否解决这个问题,以确保XML格式正确?或者你不控制XML?如果您无法控制,那可能意味着XML来自另一个域?在这种情况下,由于安全限制,JavaScript可能无法实现。 – 2011-12-29 19:51:16

回答

0
//parse the XML string (wherever it comes from), then find all the `item` tags and select their child `description` tags, now we have all the `description` tags in your XML document 
var $xml_parsed = $($.parseXML(xml_string)).find('item').children('description'); 

//now iterate through the `description` tags and find the `#dangericon` element within each 
for (var i = 0, len = $xml_parsed.length; i < len; i++) { 

    //to find an element we must create a jQuery object from the text of this `description` tag and then we can use `.find()` to search for the desired element 
    var tmp = $($xml_parsed.eq(i).text()).find('#dangericon'); 

    //you can do what you want with the element now, it is saved in the `tmp` variable 
} 

这里是一个演示:http://jsfiddle.net/pdT8S/

我假定这是被在同一个域中进行,如果是这样的话,那么你就不需要惹jsonp但如果你是在跨域调用XML文档时,您需要查看jsonp请求(只要远程服务器设置正确,就可以轻松使用jQuery进行请求)。

P.S.我是Truckee的本地人,并且愿意帮助您处理任何以滑雪为中心的网站。

+0

以下是jsfiddle的更新版本,但是找到正确元素的过程与XML文档不同:http://jsfiddle.net/BZDBF/6/ – Jasper 2011-12-29 20:24:29

+0

Hi Jasper。感谢男士的帮助。是的,这需要使用jsonp。我想我可以以某种方式将SAC feed保存到某种数据库或字符串中,然后解析它,而不会出现问题。 我真正想做的只是操纵那些显示不同的东西,就像你在那里做的那样...然而,从远程服务器。 – jasonflaherty 2011-12-29 21:00:55

+0

@buildakicker您可以使用抓取RSS提要的服务器端语言创建代理脚本(服务器端不会出现跨域问题),您的JavaScript可以引用此服务器端脚本。将服务器端脚本的响应缓存在数据库中并偶尔进行更新是个不错的主意。这样你就不会创建不必要的HTTP请求,这会增加操作的延迟。 – Jasper 2011-12-29 21:11:40