我正在使用带有ajax功能的Bootstrap typeahead,并想知道什么是正确的Json结果格式,以返回Id和描述.
我需要Id来使用mvc3模型绑定所选元素.
我需要Id来使用mvc3模型绑定所选元素.
这是代码:
- [Html]
- <input id="myTypeahead" class='ajax-typeahead' type="text" data-link="myUrl" data-provide="typeahead" />
- [Javascript]
- $('#myTypeahead').typeahead({
- source: function (query,process) {
- return $.ajax({
- url: $('#myTypeahead').data('link'),type: 'post',data: { query: query },dataType: 'json',success: function (jsonResult) {
- return typeof jsonResult == 'undefined' ? false : process(jsonResult);
- }
- });
- }
- });
- This works properly when I return a simple list of strings,for example:
- {item1,item2,item3}
- But I want to return a list with Id,for example:
- {
- {Id: 1,value: item1},{Id: 2,value: item2},{Id: 3,value: item3}
- }
如何处理这个结果在ajax“success:function()”中?
这是非常容易的jquery自动完成,因为我可以返回一个Json对象列表.
- [jquery Autocomplete process data example]
- ...
- success: function (data) {
- response($.map(data,function (item) {
- return { label: item.Id,value: item.Value,id: item.Id,data: item };
- })
- ...
但是,这并不适用于头发的头发.
有人可以帮我吗
谢谢.
解决方法
我试了两天,终于可以工作了.
Bootstrap Typeahead默认情况下不支持对象数组,只能使用字符串数组.因为“匹配器”,“分类器”,“更新器”和“荧光笔”功能需要字符串作为参数.
Bootstrap Typeahead默认情况下不支持对象数组,只能使用字符串数组.因为“匹配器”,“分类器”,“更新器”和“荧光笔”功能需要字符串作为参数.
相反,“Bootstrap”支持可定制的“匹配器”,“排序器”,“更新器”和“荧光笔”功能.所以我们可以在Typeahead选项中重写这些功能.
II使用Json格式,并将Id绑定到隐藏的html输入.
代码:
- $('#myTypeahead').typeahead({
- source: function (query,process) {
- return $.ajax({
- url: $('#myTypeahead').data('link'),success: function (result) {
- var resultList = result.map(function (item) {
- var aItem = { id: item.Id,name: item.Name };
- return JSON.stringify(aItem);
- });
- return process(resultList);
- }
- });
- },matcher: function (obj) {
- var item = JSON.parse(obj);
- return ~item.name.toLowerCase().indexOf(this.query.toLowerCase())
- },sorter: function (items) {
- var beginswith = [],caseSensitive = [],caseInsensitive = [],item;
- while (aItem = items.shift()) {
- var item = JSON.parse(aItem);
- if (!item.name.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(JSON.stringify(item));
- else if (~item.name.indexOf(this.query)) caseSensitive.push(JSON.stringify(item));
- else caseInsensitive.push(JSON.stringify(item));
- }
- return beginswith.concat(caseSensitive,caseInsensitive)
- },Highlighter: function (obj) {
- var item = JSON.parse(obj);
- var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,'\\$&')
- return item.name.replace(new RegExp('(' + query + ')','ig'),function ($1,match) {
- return '<strong>' + match + '</strong>'
- })
- },updater: function (obj) {
- var item = JSON.parse(obj);
- $('#IdControl').attr('value',item.id);
- return item.name;
- }
- });