2013-01-12 37 views
0

這裏是我的jQuery代碼從本地源如何使引導Ajax調用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: 9}, 
        { 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" } 
     ] 
    }); 

}); 

它的做工精細設置引導typehead。 如何從服務器做一個AJAX調用和掛鉤一個類似的數據如上所示與源。

update 這裏是的jsfiddle http://jsfiddle.net/MMarW/

一個以上的工作代碼和這裏是的jsfiddle Ajax代碼不點火http://jsfiddle.net/FZP8a/3/

回答

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中wece功能。更多信息在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 
    }); 
    } 
}); 

獲取有關JSONP在jQuery.ajax docs

爲$就更多信息,實際上$不用彷徨只是一個簡寫。

+0

我得到的數據作爲JSONP,所以我必須使用jsonpcallback功能,所以在DAT情況下,我怎麼能使用.success – iJade

+0

我編輯我的回答是 – usoban

+0

有可能使用一個回調函數,而不是成功 – iJade