2011-12-29 81 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