BootstrapPlugin - typeahead-ex 使用笔记

本文介绍了一个针对 Bootstrap 官方 typeahead 插件的扩展实现,该扩展增加了通过 AJAX 获取数据的功能,并提供了示例代码及 SpringMVC 的控制器实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

BootstrapPlugin - typeahead-ex 使用笔记

1) bootstrap官方的typeahead插件不支持ajax方式展示数据。这个插件作为扩展,让typeahead有了ajax的功能。
留档备份。

2) 官方文档 & 官方DEMO
[url]https://github.com/tcrosen/twitter-bootstrap-typeahead[/url]

3) 代码

<!DOCTYPE HTML>
<html lang="zh">
<head>
<title>Bootstrap Base</title>
<base href="<%=basePath %>" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link type="text/css" rel="stylesheet" href="css/bootstrap.min.css" />

<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/bootstrap-typeahead-ex.js"></script>
<script type="text/javascript" src="js/mockjax.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("[rel='tooltip']").tooltip({placement: "right"});


$('#input1').typeahead({
source: [
{ id: 1, name: 'Toronto' },
{ id: 2, name: 'Montreal' },
{ id: 3, name: 'New York' },
{ id: 4, name: 'Buffalo' },
{ id: 5, name: 'Boston' },
{ id: 6, name: 'Columbus' },
{ id: 7, name: 'Dallas' },
{ id: 8, name: 'Vancouver' },
{ id: 9, name: 'Seattle' },
{ id: 10, name: 'Los Angeles' }
],
display: 'name',
val: 'id',
itemSelected: function(item, value, text) {
alert(value);
alert(text);
}
});

// ----------------------------------------------------------------------


$('#input2').typeahead({
ajax: {
url: "ajax/test",
method: "GET",
triggerLength: 1,
preProcess: function(data) { // 这个方法非常重要!
// 本插件要求处理一个javascript对象而不是一个json字符串
// 同时应当注意 $.parseJSON方法要求的json字符串必须用双引号引用属性名!
return $.parseJSON(data);
}
},
itemSelected: function(item, value, text) {
alert(value);
alert(text);
}
});
});
</script>

</head>
<body>
<label>输入框1 <input type="text" id="input1" /></label>
<br/>
<label>输入框2 <input type="text" id="input2" /></label>
</body>
</html>


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/ajax")
public class AjaxController {

@ResponseBody
@RequestMapping(value = "/test", method = { RequestMethod.GET })
public String test(@RequestParam("query") String query)
{
return "[{ \"id\": 1, \"name\": \"New York\" }, { \"id\": 2, \"name\": \"Shanghai\"}]";
}
}

:)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值