2012-08-24 25 views
2

我在過去的3個小時隨處搜索,找不到任何可以幫助我的東西。如果有任何答案,我很抱歉,但我無法做到。搜索XML文件並用javascript顯示結果

所以我有這個xml文件如:

<entry> 
    <title>The Title</title> 
    <description>Description here</description> 
</entry> 

所以我喜歡做的事情是有它的搜索表單的HTML,然後根據搜索項顯示的所有結果在相同的頁面(例如空白div)內匹配該術語。

會這樣嗎?

很多人提前感謝任何人可以幫助我!

回答

7

我對此珍玩,並沒有回答,所以我嘗試了一些東西,大桶出來做這與jQuery

的test.xml

<item> 
    <entry> 
     <title>The Title</title> 
     <description>Description here</description> 
    </entry> 

    <entry> 
     <title>The Title 2 </title> 
     <description>Description here second</description> 
    </entry> 
</item> 

的index.html

最簡便的方法
<!DOCTYPE html> 
<html> 
<head> 
    <script src="http://code.jquery.com/jquery-latest.js"></script> 
</head> 
<body> 
<input type="text" id="search" autocomplete="off" /> 
<p id="output"></p> 

<script type="text/javascript"> 
$(document).ready(function(){ 
    $('#search').on('keyup', function(){ 
     $.ajax({ 
      type: "GET", 
      url: "test.xml", 
      dataType: "xml", 
      success: parseXML 
     }); 
    }); 
}); 
function parseXML(xml){ 
    var searchFor = $('#search').val(); 
    var reg = new RegExp(searchFor, "i"); 
    $(xml).find('entry').each(function(){ 
     var title = $(this).find('title').text(); 
     var titleSearch = title.search(reg); 
     var desc = $(this).find('description').text(); 
     var descSearch = desc.search(reg); 
     $('#output').empty(); 
     if(titleSearch > -1){ 
      $('#output').append('Found <i>'+searchFor+'<\/i> in title: '+title.replace(reg, '<b>'+searchFor+'</b>')+'<br \/>'); 
     } 
     if(descSearch > -1){ 
      $('#output').append('Found <i>'+searchFor+'<\/i> in description: '+desc.replace(reg, '<b>'+searchFor+'</b>')+'<br \/>'); 
     } 
    });  
} 
</script> 
</body> 
</html> 
+0

謝謝你!有幾個更新它像一個魅力工作! – Jaypee