使用 javascript 搜索 XML 文件并显示结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12118057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search an XML file and display results with javascript
提问by Jaypee
I have been searching everywhere for the last 3 hours and I couldn't find anything that could help me. I'm very sorry if there are any answer around but I just couldn't get to it.
在过去的 3 个小时里,我一直在到处寻找,但找不到任何可以帮助我的东西。如果周围有任何答案,我很抱歉,但我无法回答。
So I have this xml file eg:
所以我有这个 xml 文件,例如:
<entry>
<title>The Title</title>
<description>Description here</description>
</entry>
So the thing I'd love to do is to have an html with a search form in it and then based on the search term display all the results within the same page (empty div for example) that matches that term.
所以我想做的事情是在其中包含一个带有搜索表单的 html,然后根据搜索词在同一页面(例如空 div)中显示与该词匹配的所有结果。
Would that be possible?
那可能吗?
MANY thanks in advance for anyone that can help me on this!
非常感谢任何可以帮助我的人!
回答by Mihai Iorga
I was curios about this, and none answered so I tried some things and tuns out best and easy way to do this is with jQuery
我对此很感兴趣,但没有人回答,所以我尝试了一些事情,并发现最好和最简单的方法是使用 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
索引.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>