typeahead / filter / JSON解析?

时间:2016-01-06 04:54:44

标签: json typeahead bloodhound

尝试解析/阅读'我的预先输入代码上的外部.json文件,但.json文件(我无法修改)看起来像:

{"**cms_countries**":
  [{"**cms_country**": 
[{"**countrydisplayname**":"Afghanistan"}
 ,{"countrydisplayname":"Albania"} ,{"countrydisplayname":"Algeria"}
 ... ... ... ,{"countrydisplayname":"Zimbabwe"} ] } ,{"TotalRecords": 
 [ {"TotalRecords":"246"} ] } ] }

所以,我认为我的问题是要知道如何解析/读取/同化/集成/采用这个.json文件, cms_countries cms_country , 然后,我的 countrydisplayname 字段就可以了。 (你在这里见过那棵树吗?)

这是我的代码:

$(document).ready(function() {

        var searchablePlaces    = new Bloodhound({
        datumTokenizer                  : Bloodhound.tokenizers.obj.whitespace("countrydisplayname"),
        queryTokenizer                  : Bloodhound.tokenizers.whitespace,
        prefetch                        : 'countries.json',
        remote                          : {
            url                             : 'countries/%QUERY.json',
            wildcard                        : '%QUERY',
            filter                          : function(response) { return response.cms_country; }
            }, 
        limit                           : 10
        });

searchablePlaces.initialize(); 

        $('#remote .typeahead').typeahead(
        {
        hint            : true,
        highlight       : true,
        minLength       : 2
        },
        {
        name            : 'countrydisplayname',
        displayKey      : "countrydisplayname",
        source          : searchablePlaces.ttAdapter()
        })
});

但当然,它不起作用:

有关如何整理我的过滤器的任何提示......?或如何克服我的nested .json包装....

1 个答案:

答案 0 :(得分:0)

好的,我的代码现在正在运行:

$(window).load(function(){   
    var movies = new Bloodhound({
        limit: 10,
        datumTokenizer: function (d) {
            return Bloodhound.tokenizers.whitespace(d.value);
        },
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        prefetch: { 
            url: 'countries.json',
            filter: function (movies) {  
                return $.map(movies.cms_countries[0].cms_country, function (paises) {  
                    return {        
                        value: paises.countrydisplayname 
                    };
                });
            }
        }
    });

    // Initialize the Bloodhound suggestion engine
    movies.initialize(); 

    // Instantiate the Typeahead UI
    $('.typeahead').typeahead(
        {
            hint: true,
            highlight: true,
            minLength: 1
        }, 
        {
        //displayKey: 'value',
        displayKey: function (toto) {
                  return toto.value;
              },
        source: movies.ttAdapter()
    });
}); 
相关问题