Autocomplete-Java 中的 Jquery Ajax Json 示例(使用 Servlet)
这里使用 devbridge jquery api 来实现自动完成功能。
要求:
Eclipse
Mysql(或者你可以使用任何其他数据库,但在 lib 文件夹中你必须添加适当的驱动程序
对于该数据库)
获取国家/地区列表
对于 MySQL
https://github.com/bharathirasa/demo/blob/master/mysql-country-list-codes.sql
对于甲骨文
https://github.com/bharathirasa/demo/blob/master/oracle-country-list.sql
HTML 代码
<input type="text" name="country" id="autocomplete"
class="form-control" placeholder="Enter Country name" />
Jquery 代码
$("#autocomplete").autocomplete({
//lookup: countries,
serviceUrl:'Auto', //tell the script where to send requests
width: 450, //set width
//callback just to show it's working
onSelect: function (suggestion) {
$('#selection').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
},
showNoSuggestionNotice: true,
noSuggestionNotice: 'Sorry, no matching results',
});
Servlet 代码
String q=request.getParameter("query");
ArrayList<Country> o=CountryDao.getCountryName(q);
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(o);
//System.out.println(json);
response.getWriter().write("{\"suggestions\":"+json+"}");
这里没有提到方法,所以所有的数据都将作为 GET 方法传递。如果您想通过 Jquery 中的帖子提及来传递数据,例如 type:'POST'。
嗨,实际上我使用 devbridge jquery api 在 java 中创建了一个自动完成功能
点击链接获取更多信息
http://pdfboxtutorial.blogspot.com/2015/03/autocomplete-jquery-ajax-json-example.html