如何在bootstrap typeahead中进行ajax调用

时间:2013-01-12 07:25:25

标签: javascript jquery bootstrap-typeahead

这是我的jquery代码,用于从本地源

设置bootstrap typehead
    $(function () {

    var src = [{ id: 1, name: 'Toronto', state: 'ON', country: 'Canada', key: 12345 },
                    { id: 2, name: 'Montreal', state: 'QC', country: 'Canada', key: 23456 },
                    { id: 3, name: 'New York', state: 'NY', country: 'USA', key: 34567 },
                    { id: 4, name: 'Buffalo', state: 'NY', country: 'USA', key: 45678 },
                    { id: 5, name: 'Boston', state: 'MA', country: 'USA', key: 56789 },
                    { id: 6, name: 'Columbus', state: 'OH', country: 'USA', key: 67890 },
                    { id: 7, name: 'Dallas', state: 'TX', country: 'USA', key: 78901 },
                    { id: 8, name: 'Vancouver', state: 'BC', country: 'Canada', key: 89102 },
                    { id: 9, name: 'Seattle', state: 'WA', country: 'USA', key: 90123 },
                    { id: 10, name: 'Los Angeles', state: 'CA', country: 'USA', key: 11234}];

    localStorage.setItem("cities", JSON.stringify(src));

    $('#search').typeahead({
        sources: [
        { name: "local", type: "localStorage", key: "cities" }
      ]
    });

});

工作正常。 如何从服务器进行ajax调用,并使用源连接上面显示的类似数据。

update 的 这是jsfiddle http://jsfiddle.net/MMarW/

上面的上述工作代码

这是jsfiddle上没有触发http://jsfiddle.net/FZP8a/3/

的ajax代码

1 个答案:

答案 0 :(得分:0)

提供功能作为来源:

$('#search').typeahead({
  source: function(query, process) {
    var searchUrl = YOUR_URL + '?q=' + encodeURIComponent(query);

    $.get(searchUrl)
    .success(function(data){
      //... do whatever you want...
      // ... and pass array to process function
      process(dataArray);
    })
    .error(function(){
      //...handle error
    });
  }
});

您也可以直接从源函数返回dataArray。有关选项中docs的更多信息。

编辑:要请求jsonp,请使用jQuery.ajax:

$('#search').typeahead({
  source: function(query, process) {
    var searchUrl = YOUR_URL + '?q=' + encodeURIComponent(query);

    $.ajax(searchUrl, {
       dataType: 'jsonp',
       crossDomain: true // probably needed
    }).success(function(data){
      //... do whatever you want...
      // ... and pass array to process function
      process(dataArray);
    }).error(function(){
      //...handle error
    });
  }
});

jQuery.ajax docs

中获取有关jsonp的更多信息

实际上$ .get只是$ .ajax的简写。