0

i use Twitter Bootstrap and typeahead.

i download the plugin: Twitter Bootstrap Typeahead Plugin Extension

and so long so good, its working when i use a static javascript json array eg.

$('#demo1').typeahead({
        source: [
            { id: 9000, name: 'Aalborg' },
            { id: 2, name: 'Montreal' },
            { id: 3, name: 'New York' },
            { id: 4, name: 'Buffalo' },
            { id: 5, name: 'Boston' },
            { id: 6, name: 'Columbus' },
            { id: 7, name: 'Dallas' },
            { id: 8, name: 'Vancouver' },
            { id: 9, name: 'Seattle' },
            { id: 10, name: 'Los Angeles' }
        ],
        itemSelected: displayResult
    });

When i try to use ajax its will do enerything, my code look like this.

$('.typeahead').typeahead({
            ajax: '/actions/search/synonymSearch',
            itemSelected: displayResult
        });

and its return this json array ( i can rebuild its on all ways, and i can't get it to work )

[
    { id: 1, name: 'Toronto' },
    { id: 2, name: 'Montreal' },
    { id: 3, name: 'New York' },
    { id: 4, name: 'Buffalo' },
    { id: 5, name: 'Boston' },
    { id: 6, name: 'Columbus' },
    { id: 7, name: 'Dallas' },
    { id: 8, name: 'Vancouver' },
    { id: 9, name: 'Seattle' },
    { id: 10, name: 'Los Angeles' }
]

The plugin home pages. https://github.com/tcrosen/twitter-bootstrap-typeahead

i hobe enybardy can help me here :)

thanks a lot for all helping, :)

EDIT - Problem resovle! :) Just need to added header("content-type: application/json"); into my PHP file, hobe this answere are usefull for orther peopole! :)

4

2 回答 2

0

您遇到的这个问题可能是由于您通过 ajax 调用的页面没有返回正确的标题。

如果您使用的是 PHP,请尝试添加header('Content-type: application/json');到包含 JSON 数组的文档中。

于 2013-03-18T04:33:47.167 回答
0

我认为typeahead无法读取source您的数组,因此我会先对其进行解析。

var data = [{"id":"9000","name":"Aalborg"},{"id":"9220","name":null},{"id":"9210","name":null},{"id":"9200","name":"Aalborg SV"}];

// using underscore.js get an array of the city names
var cities = _.pluck(data, "name");

// now start typeahead
$el.typeahead(
    source: cities,
    // the value of the `city` selected gets passed to the onselect  
    onselect: function(city) {
         // get the index of city selected from the data array
         var i = _.indexOf(data, city);
         // then using the index get what ever other value you need from the array
         // and insert in the DOM etc..

    }
);
于 2012-10-29T09:33:41.477 回答