2012-06-24 47 views
0

我有下面的代碼,如果我使用2.0.0版本,肯定會返回正確的數據結果,但由於某些原因bootstrap的typeahead插件給我一個錯誤。我粘貼它的代碼示例如下:twitter引導typeahead 2.0.4 ajax錯誤

<input id="test" type="text" /> 

$('#test').typeahead({ 
    source: function(typeahead, query) { 
     return $.post('/Profile/searchFor', { query: query }, function(data) {     
      return typeahead.process(data); 
     }); 
    } 
}); 

當我運行這個例子中,我得到一個jQuery的錯誤,說以下內容:

** 
item is undefined 
matcher(item=undefined)bootst...head.js (line 104) 
<br/>(?)(item=undefined)bootst...head.js (line 91) 
<br/>f(a=function(), b=function(), c=false)jquery....min.js (line 2) 
<br/>lookup(event=undefined)bootst...head.js (line 90) 
<br/>keyup(e=Object { originalEvent=Event keyup, type="keyup", timeStamp=145718131, more...})bootst...head.js (line 198) 
<br/>f()jquery....min.js (line 2) 
<br/>add(c=Object { originalEvent=Event keyup, type="keyup", timeStamp=145718131, <br/>more...})jquery....min.js (line 3) 
<br/>add(a=keyup charCode=0, keyCode=70)jquery....min.js (line 3) 
<br/>[Break On This Error] 
<br/>return item.toLowerCase().indexOf(this.query.toLowerCase())** 

有什麼想法? ...相同的代碼在2.0.0版本的插件中工作,但未能寫入我的挖空對象模型。

這是工作預輸入代碼,版本2.0.0:

var searchFunction = function(typeahead, query) { 
     $.ajax({ 
      url: "/Profile/searchFor?tableName=" + tableName + "&query=" + query + "&extendedData=" + $("#" + extendedData).val(), 
      success: function(data) { 
       if (data.errorText != null) { 
        toggleLoading("false"); 
        showDialog(data.errorText, "Error"); 
        return; 
       }     
       var result = data.results.split("::"); 
       typeahead.process(result); 
      }, 
      select: function(event, ui) { 
      } 
     }); 
    } 

    $("#" + inputBoxId).typeahead({ 
     source: searchFunction, 
     onselect: function(obj) { 
     } 
    }); 
+0

什麼是完整的錯誤請 – Esailija

+0

在原始文章中添加了更多信息。 –

+1

在Bootstrap typeahead'source'必須是一個數組。 http://twitter.github.com/bootstrap/javascript.html#typeahead – Esailija

回答

4

1)引導預輸入V2.0.2解決方案

看看this pull request,它看起來像你在找什麼(它是引導類型v2.0.2中的一個分支)。

我用它自己,它的工作正在進行解決方案

:)

2)引導預輸入v.2.1.0工作,你也可以嘗試this solution。我只是改變了我的項目中使用這一個,becouse它會在未來的版本中得到支持,它看起來更清潔:)

在我的情況:

$("#typeahead").typeahead({ 
    source: function(query, process) { 
    $.post('url_path', { q: query, limit: 4 }, function(data) { 
     process(data); 
    }); // end of post 
    } 
}); 

當腳本url_path requiers 2個參數q (字符串)和限制(結果極限),並返回JSON響應(數組):

實施例響應於查詢與限制:

[ 「阿姆」, 「軟綿綿的Bizkit」, 「蕾哈娜」, 「威爾·史密斯」]

2

人們試圖生成JSON數據(不使用PHP的json_encode)和想知道爲什麼bootstrap-typeahead fork by Terry Rosen不會在Ajax調用工作

返回的JSON數據的格式必須是以下形式: -

[{「ID」:「1」,「名」:「老車「},{」id「:」2「,」name「:」Castro trolley car「},{」id「:」3「,」name「:」 「},{」 ID「:」 4" ,‘名’:‘把車停在古董行汽車’}]

注意引號

已經花了一整天試圖找出什麼問題是的,我認爲在這裏發佈是明智的。也許,我對JSON的理解是錯誤的,但是即使id和name字段沒有被引用,firebug也會將返回的數據顯示爲有效的JSON。而且,響應頭應該設置爲'application/json'。希望這可以幫助某人。

+0

我有這兩個問題 - 舊的JSON格式和響應頭沒有設置爲應用程序/ JSON和這個答案救了我。 – ThisGuy

1

在版本2.0.4上,typeahead是越野車,不接受函數作爲源,只接受數組。我升級到2.1,並按預期工作。