搜索XML文件并使用javascript显示结果

问题描述 投票:2回答:1

我一直在寻找最近3个小时的地方,我找不到任何可以帮助我的东西。我很抱歉,如果有任何答案,但我无法达到它。

所以我有这个xml文件,例如:

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

所以我喜欢做的事情就是在其中添加带有搜索表单的html,然后根据搜索词显示匹配该术语的同一页面中的所有结果(例如空div)。

这可能吗?

非常感谢任何可以帮助我的人!

javascript xml search
1个回答
7
投票

我很好奇这个,没有人回答,所以我尝试了一些东西,结果是最好的,简单的方法来做这个是用jQuery

test.hml

<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>
© www.soinside.com 2019 - 2024. All rights reserved.