bootstrap-typeahead的ajax调用

来源:互联网 发布:编程书 编辑:程序博客网 时间:2024/05/19 16:51
    我本人写过很多的自动匹配脚本,但是一牵扯到ajax后台调用,总是感觉相当麻烦,这段时间有一个小项目又要用到类似的组件,我痛下决心搞一个好的经过一下午的比较和使用发现了一个相当不错件那就是twitter-bootstrap-typeahead-master
  这个组件和bootstrap-typeahead原装的不太一样,因为原装的对ajax竟然没有支持,如果写的话很费劲,而twitter-bootstrap-typeahead-master这个项目则在原版的基础上增加了ajax的功能,着实解决了很多问题,不过这个组件也有不好的地方,就是没有类似于Jquery插件autocomplete的mustMatch属性(如果设置true,autoComplete只会允许匹配的结果出现在输入框,所有当用户输入的是非法字符时将会得不到下拉框),所以经过改造后也实现了这个功能,现在我研究的一些心得与大家分享一下。
     首先下载twitter-bootstrap-typeahead-master这个组件。
     下载地址:
          http://download.csdn.net/detail/ltllml44/9634157
          https://github.com/tcrosen/twitter-bootstrap-typeahead

开发前需要版本
  • Twitter Bootstrap 2.0+
  • jQuery 1.7+

解压后只需要引用如下包即可
<link href="/path/to/bootstrap.css" rel="stylesheet">
<script src="/path/to/jquery.js" type="text/javascript"></script>
<script src="/path/to/bootstrap-typeahead.js" type="text/javascript"></script>
官方的API:

Events

EventDescriptiongrepperFilters relevant results from the source.highlighterHighlights any matching results in the list.itemSelected
  • 当选中一个项目时的回调函数.
    • item: 选中的 HTML 元素
    • val: *val* 属性的值
    • text: *display* 属性的值
lookupDetermines if source is remote or local and initializes the search.matcherLooks for a match between the query and a source item.renderRenders the list of results.selectSelects an item from the results list.sorterSorts the results.


Options

NameTypeDefaultDescriptionajaxobject
{    url: null,(1)    timeout: 300,(2)    method: 'post',(3)    triggerLength: 3,(4)    loadingClass: null,    displayField: null,    preDispatch: null,(5)     preProcess: null(6)
}
The object required to use a remote datasource. 
See also: ajax as a string (below)ajaxstringnullOptionally, a simple URL may be used instead of the AJAX object. 
See also: ajax as an object (above)displaystring'name'  (7)The object property to match the query against and highlight in the results.itemstring'<li><a href="#"></a></li>'The HTML rendering for a result item.itemsinteger8   (9)The maximum number of items to show in the results.menustring'<ul class="typeahead dropdown-menu"></ul>'The HTML rendering for the results list.sourceobject[]The source to search against.valstring'id' (8)The object property that is returned when an item is selected.

API重点说明
(1) url:顾名思义,需要传一个后台的路径。
(2) timeout: 延时加载 
(3) method:提交方式
(4)tiggerLength:输入几个汉字后开始请求后台。
(5)preDispatch: 发出请求前调用的预处理方法
(6)preProcess:发出请求后的调用方式
(7)display:默认的对象属性名称
(8)val:默认的标识属性名称
(9)tiems:下拉列表最多显示几个

前台开发,官方提供的例子比较简单。
    
 $('#demo3').typeahead({        source: [            { id: 1, full_name: 'Toronto', first_two_letters: 'To' },            { id: 2, full_name: 'Montreal', first_two_letters: 'Mo' },            { id: 3, full_name: 'New York', first_two_letters: 'Ne' },            { id: 4, full_name: 'Buffalo', first_two_letters: 'Bu' },            { id: 5, full_name: 'Boston', first_two_letters: 'Bo' },            { id: 6, full_name: 'Columbus', first_two_letters: 'Co' },            { id: 7, full_name: 'Dallas', first_two_letters: 'Da' },            { id: 8, full_name: 'Vancouver', first_two_letters: 'Va' },            { id: 9, full_name: 'Seattle', first_two_letters: 'Se' },            { id: 10, full_name: 'Los Angeles', first_two_letters: 'Lo' }        ],        display: 'full_name'    });
如果不用ajax 其实将数据格式封装成入上代码所示就足够了。
通过阅读源码,我增加并实现了mustMatch的功能(只会允许匹配的结果出现在输入框,所有当用户输入的是非法字符时将会得不到下拉框)。

核心代码的主要思想是:当文本输入框失去焦点的时候,判断当前输入的值,是不是能与下拉列表中的数匹配,如果不匹配则清空,并且高亮显示。(修改后的源码请在文章结尾处获取)
blur: function (e) {
var val = this.$element.val();
this.focused = false
if(this.uploadData(val)==""){//增加的代码
this.$element.css("border","solid red 1px")
}else{
this.$element.css("border","solid green 1px")
}
this.$element.val(this.uploadData(val))
if (!this.mousedover && this.shown) this.hide()
}
具体使用方法如下:
<script type="text/javascript">
 
var data = [
{ id: "巴厘岛", name: "巴厘岛" },
{ id: "日本", name: "日本" },
{ id: "爱尔兰", name: "爱尔兰" },
{ id: "北欧", name: "北欧" },
{ id: "希腊", name: "希腊" },
{ id: "捷克", name: "捷克" },
{ id: "意大利", name: "意大利" },
{ id: "越南", name: "越南" },
{ id: "迪拜", name: "迪拜" },
{ id: "斯洛伐克", name: "斯洛伐克" },
{ id: "柬埔寨", name: "柬埔寨" },
{ id: "马耳代夫", name: "马耳代夫" },
{ id: "德法瑞意", name: "德法瑞意" },
{ id: "北欧1", name: "北欧1" },
{ id: "北欧2", name: "北欧2" }];
 
 
$(document).ready(function() {
$('#search').typeahead({
source: data,
uploadData:function(item){
var arrayData = new Array();
$.each(data, function (n, value) {//循环比较
arrayData.push(value.name);
});
var index = $.inArray(item,arrayData);
if(index==-1){
return ""; //如果不匹配清空
}
return item; //如果匹配则显示
}
});
});
</script>

ajax方式获取后台数据
$("#respondentName").typeahead({
ajax: {
url: "${ctx}/order/capBusiOrder/listLegalUnit",
timeout: 100,
displayField: "horsortName",
triggerLength: 1,
dataType: 'JSON',
method: "get",
loadingClass: "loading-circle",
preDispatch: function (query) {
return {
horsortName: query, //查询条件
limit: 5, //一次只查询5条
}
},
preProcess: function(data) { // 这个方法非常重要!
// 本插件要求处理一个javascript对象而不是一个json字符串
// 同时应当注意 !
return $.parseJSON(data); //非常重要
}
 
},
display:'horsortName',
val:'id',
items:5,
itemSelected:function(item, value, text) {
//alert(item);//object 对象
//alert(text); //选中的名称s
}
,
uploadData:function(item){//什么都可以通过。不许要做匹配验证则写成如下这种方案
return item;
}
});

修改的代码下载地址如下:
http://download.csdn.net/detail/ltllml44/9634236




1 0
原创粉丝点击