如何在JSON文件中搜索?

时间:2015-12-13 19:15:43

标签: javascript php json

我如何创建一个搜索表单来搜索JSON文件中输入的术语?

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

我创建了一个搜索输入:

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

我的JSON看起来像这样:

{
    "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"
        }

    ]
}

更新

我想出了以下内容,使用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');
            });

        });

这是有效的,只应输入与JSON中存储的完全相同的内容。 因此,当您搜索“意大利”并使用小写类型时,它将找不到该对象。当您搜索示例时,它也不会给出任何条目:ne。我想将荷兰和纽约作为搜索结果。

4 个答案:

答案 0 :(得分:1)

解决方案有几个步骤,让我们知道您不能做的步骤:

  1. 当用户点击按钮
  2. 时调用JS函数
  3. 将服务器上磁盘中的文件读入浏览器中的JS变量
  4. 使用lodash.js从搜索词的JS变量中获取网址
  5. 向用户显示结果
  6. 但是我最简单的回答就是这样做:

    使用页面加载JSON文件,就像任何Javascript文件一样。 加载lodash.js。

    调用你的JSON文件towns.js并使它看起来像这样:

    var cities = 
    {
        "title":    "Locations",
        "locations":    
        [
            {
                "title":        "New York",
                "url":          "api/newyork.js"
            },
            {
                "title":        "Dubai",
                "url":          "api/dubai.js"
            }
        ]
    }
    

    然后你的HTML是这样的:

    <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>
    

答案 1 :(得分:1)

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

试试吧。

// testData is defined for demo only. Can be removed
var testData = [
    {
        "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"
    }
];
// Variable to hold the locations
var dataArr = {};
// Load the locations once, on page-load.
$(function() { 
    $.getJSON( "api/videoData.js").done(function(data) {
        window.dataArr = data.pages;
    }).fail(function(data) {
        console.log('no results found');
        window.dataArr = testData; // remove this line in non-demo mode
    });
});
// Respond to any input change, and show first few matches
$("#search").on('keypress keyup change input', function() { 
    var arrival = $(this).val().toLowerCase();
    $('#matches').text(!arrival.length ? '' : 
        dataArr.filter(function(place) {
            // look for the entry with a matching `code` value
            return (place.title.toLowerCase().indexOf(arrival) !== -1);
        }).map(function(place) {
            // get titles of matches
            return place.title;
        }).join('\n')); // create one text with a line per matched title
});
// submit button is not needed really
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="search" type="text" placeholder="Search term">
<div id="matches" style="height:70px; overflow-y:hidden; white-space:pre"></div>

答案 2 :(得分:0)

正如您在更新中使用此代码所述:

  

所以当你搜索&#34;意大利&#34;并且您使用小写类型,它将找不到该对象。当你搜索例子时,它也不会给出任何条目:ne。我想将荷兰和纽约作为搜索结果。

$(&#34; #search&#34;)。change(function(){             var arrival = $(this).val();

function initialize(ipList)
{
    var locations = [];
    var ips = ipList;
    var apiUrl = 'http://freegeoip.net/json/';


//    for(var i = 0; i < ips.length; i++)
//    {
//        jQuery.ajax
//        ({ 
//            url: apiUrl + ips[i], 
//            type: 'POST', 
//            dataType: 'jsonp',
//            success: function(location) 
//            {
//                if(location != null)
//                {
//                    locations.push(location);;
//                }
//            }
//        });
//    }

    $.each(ips, function(i, x) 
    {
        $.ajax
        ({
            url: apiUrl + x,
            type: "POST",
            cache: false,
            success: function(data) 
            {
                if(data != null)
                {
                    locations[i] = location;
                }
            }
        });
    });

    var properties = 
    {
        center: new google.maps.LatLng(locations[0].latitude, locations[0].longitude),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map"),properties);

    for (var i = 0; i < locations.length; i++)
    {
        var marker = new google.maps.Marker
        ({
            position:{lat: locations[i].latitude, lng: locations[i].longitude},
            animation:google.maps.Animation.BOUNCE,
            title: locations[i].city
        });

        marker.setMap(map);
    }
}

替换此行:

        $.getJSON( "api/videoData.js", { arrivalDate: arrival })
        .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');
        });

    });

if (dataArr[i].title == arrival){

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

答案 3 :(得分:0)

如果您打算将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);

在表单元素(id="myForm")和'name'属性中添加一些标识符到输入字段(name="search");

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;
  }