Javascript 如何在JSON文件中搜索?

Javascript 如何在JSON文件中搜索?,javascript,php,json,Javascript,Php,Json,如何创建一个搜索表单,在JSON文件中搜索输入的术语 因此,如果搜索项等于location对象内的标题,则它应返回该对象信息。如果没有匹配项,则向用户反馈未找到任何项 我创建了一个搜索输入: <form action="" method="get"> <input id="search" type="text" placeholder="Search term"> <input type="s

如何创建一个搜索表单,在JSON文件中搜索输入的术语

因此,如果搜索项等于location对象内的标题,则它应返回该对象信息。如果没有匹配项,则向用户反馈未找到任何项

我创建了一个搜索输入:

    <form action="" method="get">               
         <input id="search" type="text" placeholder="Search term">
         <input type="submit" class="button">
   </form>
更新:

我使用jQuery得出以下结论:

$("#search").change(function() { 
            var arrival = $(this).val();

            $.getJSON( "api/videoData.js")
            .done(function(data) {
                // update your ui here
                console.dir(data.pages);
                var dataArr = data.pages;

                // Iterate over each element in the array
                for (var i = 0; i < dataArr.length; i++){
                    // look for the entry with a matching `code` value
                    if (dataArr[i].title == arrival){
                        // we found it
                        console.log(dataArr[i].title);
                    } else {
                        console.log('Houston, we have a problem');
                    }
                }

            }).fail(function(data) {
            // handle error here
                console.log('no results found');
            });

        });
$(“#搜索”).change(函数(){
var arrival=$(this.val();
$.getJSON(“api/videoData.js”)
.完成(功能(数据){
//在此处更新您的ui
console.dir(数据页);
var dataArr=data.pages;
//迭代数组中的每个元素
对于(变量i=0;i
这是可行的,只是输入的内容应该与JSON中存储的内容完全相同。
因此,当您搜索“Italy”并使用小写类型时,它将找不到对象。当您搜索时,它也不会给出任何条目,例如:
ne
。我希望获得荷兰和纽约作为搜索结果。

解决方案有几个步骤,请告知您不能执行的步骤:

  • 当用户单击按钮时调用JS函数
  • 将文件从服务器上的磁盘读取到浏览器中的JS变量中
  • 使用lodash.js从搜索词的js变量中获取url
  • 向用户显示结果

  • 但我想尝试一下最简单的答案,我会这么做:

    与任何Javascript文件一样,在页面中加载JSON文件。 加载lodash.js

    调用JSON文件towns.js,使其如下所示:

    {
        "title":    "Locations",
        "locations":    [
            {
                "title":        "New York",
                "url":          "api/newyork.js"
            },{
                "title":        "Dubai",
                "url":          "api/dubai.js"
            },{
                "title":        "Netherlands",
                "url":          "api/netherlands.js"
            },{
                "title":        "Lanzarote",
                "url":          "api/lanzarote.js"
            },{
                "title":        "Italy",
                "url":          "api/italy.js"
            }
    
        ]
    }
    
    var cities = 
    {
        "title":    "Locations",
        "locations":    
        [
            {
                "title":        "New York",
                "url":          "api/newyork.js"
            },
            {
                "title":        "Dubai",
                "url":          "api/dubai.js"
            }
        ]
    }
    
    <input type="" class="button" onclick='go()'>
    
    <script src='towns.js' />
    <script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js' />
    <script>
        function go()
        {
            var name = document.getElementById('search').value;
            var result = _.find(cities.locations, {'title': name});
            if (!result)
                window.alert('Nothing found');
            else
                window.alert('Go to ' + result.url);
        }
    <script>
    
    然后你的HTML是这样的:

    {
        "title":    "Locations",
        "locations":    [
            {
                "title":        "New York",
                "url":          "api/newyork.js"
            },{
                "title":        "Dubai",
                "url":          "api/dubai.js"
            },{
                "title":        "Netherlands",
                "url":          "api/netherlands.js"
            },{
                "title":        "Lanzarote",
                "url":          "api/lanzarote.js"
            },{
                "title":        "Italy",
                "url":          "api/italy.js"
            }
    
        ]
    }
    
    var cities = 
    {
        "title":    "Locations",
        "locations":    
        [
            {
                "title":        "New York",
                "url":          "api/newyork.js"
            },
            {
                "title":        "Dubai",
                "url":          "api/dubai.js"
            }
        ]
    }
    
    <input type="" class="button" onclick='go()'>
    
    <script src='towns.js' />
    <script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js' />
    <script>
        function go()
        {
            var name = document.getElementById('search').value;
            var result = _.find(cities.locations, {'title': name});
            if (!result)
                window.alert('Nothing found');
            else
                window.alert('Go to ' + result.url);
        }
    <script>
    
    
    函数go()
    {
    var name=document.getElementById('search')。值;
    var result=\.find(cities.locations,{'title':name});
    如果(!结果)
    window.alert(“未找到任何内容”);
    其他的
    window.alert('转到'+result.url));
    }
    
    正如您在更新代码时所说:

    因此,当您搜索“Italy”并使用小写类型时,它将找不到对象。当您搜索时,它也不会给出任何条目,例如:ne。我想得到荷兰和纽约作为搜索结果

    $(“#搜索”).change(函数(){ var arrival=$(this.val()

    为了


    现在,它将匹配包含您正在搜索的字符串的所有字符串…

    如果您希望json文件是静态的,而不是非常大的,那么最好在页面加载事件中立即加载它(防止多次发送相同的请求)。尝试此方法:

    var xhr = new XMLHttpRequest(),
            locations = {};
    
    xhr.overrideMimeType("application/json");
    xhr.open('GET', 'locations.json', true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == "200") {
            var content = JSON.parse(this.response),
                    locations_arr, i, count, title;
    
            locations_arr = content['locations'];
            for (i = 0, count = locations_arr.length; i < count; i++) {
                title = locations_arr[i]['title'].toLowerCase();
                locations[title] = locations_arr[i];
            }
            console.log(locations);
        }
    
    };
    xhr.send(null);
    

    下面是一个演示如何进行查找的片段。它只加载JSON一次。我已经包含了JSON请求失败时的测试数据,它将在本演示中提供。每次更改输入值时,
    input
    下面的
    div
    中都会显示一个简短的匹配列表。不包括提交按钮,因为电子搜索是即时的

    试试看

    //testData仅为演示定义。可以删除
    var testData=[
    {
    “标题”:“纽约”,
    “url”:“api/newyork.js”
    },{
    “头衔”:“迪拜”,
    “url”:“api/dubai.js”
    },{
    “标题”:“荷兰”,
    “url”:“api/nertherlands.js”
    },{
    “标题”:“兰扎罗特”,
    “url”:“api/lanzarote.js”
    },{
    “头衔”:“意大利”,
    “url”:“api/italy.js”
    }
    ];
    //变量来保存位置
    var dataArr={};
    //在页面加载时加载位置一次。
    $(函数(){
    $.getJSON(“api/videoData.js”).done(函数(数据){
    window.dataArr=data.pages;
    }).失败(功能(数据){
    console.log(“未找到结果”);
    window.dataArr=testData;//在非演示模式下删除此行
    });
    });
    //响应任何输入更改,并显示前几个匹配项
    $(“#搜索”).on('keypress keyup change input',function(){
    var arrival=$(this.val().toLowerCase();
    $(“#匹配”)。文本(!arrival.length?“”:
    数据阵列过滤器(功能(位置){
    //查找具有匹配“code”值的条目
    return(place.title.toLowerCase().indexOf(arrival)!=-1);
    }).地图(功能(地点){
    //获取比赛的标题
    返回地点、名称;
    }).join('\n');//创建一个文本,每个匹配的标题有一行
    });
    //确实不需要提交按钮
    
    
    您自己尝试过javascript吗?如果是,请提供code@depperm,还没有。我不知道当用户单击“提交”按钮时如何获取该值,然后将搜索该词。。对于小写和部分匹配,只需说:u.startsWith(dataArr[I].title.toLowerCase(),arrival.toLowerCase())为什么要通过arrivaldate URL参数传递搜索值?是否要传递在另一个输入中输入的日期?能否在问题中澄清这一点?谢谢你提及。我认为这不应该是代码的一部分。我将其从代码中删除。我在一秒钟前更新了我的答案,也许你可以帮助我。我会的现在试试你的代码!我应该用你修改过的代码替换哪一行?
    document.getElementById('myForm').onsubmit = function() {
        var search_value = this.search.value.trim().toLowercase();
        if (search_value && location[search_value]) {
           console.log(location[search_value]);
        } else {
           alert("Object with specified title not found!");
        }
        // You must return false to prevent the default form behavior
        return false;
      }