2013-09-25 57 views
2

使用typeahead.js我使用使用jQuery AJAX調用

http://twitter.github.io/typeahead.js/版本0.9.3

JQuery version 2.0.3

我有下面的例子中,我正確認識作品。

<input id="subCategory" name="subCategory" type="text" /> 
<script> 
    $('#subCategory').typeahead({ 
     name: "subCategory", 
     local: ["how", "when", "where", "who", "why"], 
     limit: 10 
    }); 
</script> 

我該如何改變這一點,以便我可以使用JSON的AJAX請求的成功結果?

下面的例子不起作用,我的第一個想法是因爲它不在等待來自$.getJSON()和I的響應來輪詢更新或等待異步調用完成。

<script> 
    $('#subCategory').typeahead({ 
     name: "subCategory", 
     local: $.getJSON("/subcategories/all/"), 
     limit: 10 
    }); 
</script> 

我首先想到的是,我將不得不使用高於預輸入配置$.getJSON()功能,而不是成功的回調裏面?有沒有更好的方法來解決這個問題?

的JSON調用是一個MVC控制器動作,返回類似於下面這個簡單的例子一個JSONResult

public ActionResult All() 
    { 
     return Json(_subCategoryService.GetAll(), JsonRequestBehavior.AllowGet); 
    } 

我已經測試過,知道這getJSON要求正常工作。


UPDATE:

我還得到一點想,如果這件事和做的,而不是一個異步調用下面的,但預輸入數據顯示,1項爲undefined,但這似乎更合適不過,我只打算一次填充完整列表,然後在客戶端上過濾該列表,而不是在有人使用查詢參數輸入到輸入框中時進行此遠程調用。

<script> 
    $('#subCategory').typeahead({ 
     name: "subCategory", 
     remote: "/subcategories/all/", 
     limit: 10 
    }); 
</script> 

更新2:

我現在也正在意識到我的第一個例子是原語的一個列表,我的子類別是不是:(咄..例如:

[{ id: 1, name: "subcategory-1" }, { id: 2, name: "subcategory-2" }] 

所以現在我開始看看打字prefetch選項和filter屬性,但我真的想用t他好像它是一個下拉列表,所以要選擇ID爲後盾值列表中的一個特定條目


更新3:

因爲我試圖使用預輸入輸入就好像它是一個組合框,我已經改變了我的例子,但使用本地數據而不是我的JSON響應,下面的工作將id值存儲在隱藏字段中。

<input id="subCategorySelection" type="hidden" /> 
    <input id="subCategory" name="subCategory" type="text" /> 

<script> 
    $("#subCategory").typeahead({ 
     name: "subCategories", // the name for the dataset 
     local: [{ id: 1, name: "subcategory-1" }, { id: 2, name: "subcategory-2" }], 
     limit: 10, 
     valueKey: "name" // the value shown in the textbox 
    }).on("typeahead:selected typeahead:autocompleted", 
     function(e, datum) { 
      $("#subCategorySelection").val(datum.id); 
     } 
    ); 
</script> 

回答

1

恐怕這還沒有得到支持,至少當我在幾周前看過它時。

但是......有這個拉動請求完全符合你的要求。

https://github.com/twitter/typeahead.js/pull/220

+0

好了這個解決方案,感謝這個回答我原來的是能夠在本地參數設置爲一個問題$ .getJSON響應,我也添加了一個答案,我現在如何做,如果不使用建議的拉 – Pricey

0

下面是成功的回調中做的一個例子,但我真的不喜歡這個怎麼需要使用。

$.getJSON("/subcategories/all/", null, function(response) { 
     $("#subCategory").typeahead({ 
      name: "subCategories", // the name for the dataset 
      local: response, 
      limit: 10, 
      valueKey: "name" 
     }).on("typeahead:selected typeahead:autocompleted", 
      function(e, datum) { 
       $("#subCategorySelection").val(datum.id); 
      } 
     ); 
    }); 

現在我不需要做這個反正已經走了使用prefetch

$("#subCategory").typeahead({ 
     name: "subCategories", // the name for the dataset 
     prefetch: { 
      url: "/subcategories/all/", 
      ttl: 360000 /* 1 hour of local storage */ 
     }, 
     limit: 10, 
     valueKey: "name" 
    }).on("typeahead:selected typeahead:autocompleted", 
     function(e, datum) { 
      $("#subCategorySelection").val(datum.id); 
     } 
    );