Gon*_*alo 13 html ajax asp.net-mvc-3 twitter-bootstrap bootstrap-typeahead
我正在使用带有ajax函数的Bootstrap typeahead,并想知道什么是正确的Json结果格式,以返回Id和描述.我需要Id将typeahead选定元素与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}
}
Run Code Online (Sandbox Code Playgroud)
如何在ajax"success:function()"中处理这个结果?
使用jquery Autocomplete非常容易,因为我可以返回一个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 };
})
...
Run Code Online (Sandbox Code Playgroud)
但这不适用于boostrap Typeahead.
谁能帮我?
谢谢.
Gon*_*alo 41
我试了两天,最后我还能工作.默认情况下,Bootstrap Typeahead不支持对象数组,只支持字符串数组.因为"匹配器","分拣机","更新器"和"突出显示器"功能期望字符串作为参数.
相反,"Bootstrap"支持可定制的"匹配器","分拣机","更新器"和"荧光笔"功能.所以我们可以在Typeahead选项中重写这些函数.
II使用Json格式,并将Id绑定到隐藏的html输入.
代码:
$('#myTypeahead').typeahead({
source: function (query, process) {
return $.ajax({
url: $('#myTypeahead').data('link'),
type: 'post',
data: { query: query },
dataType: 'json',
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;
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36472 次 |
| 最近记录: |