0
我的代码应该显示用户输入的值的建议,但是我需要从后端检索建议。如何将自动完成连接到后端
我发现以下,但我想知道是否有反正使用列表而不是返回json。
下面的函数显示了如何做一个请求,后端提供建议。
函数来检索从后端
function find(value){
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("suggestions").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("get","search?input="+value,false);
xmlhttp.send();
}
建议该函数使用一个返回可被显示给用户的建议列表for循环如下
sug.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<c:forEach items="${sug}" var="mysug">
<label id="suggestion" onclick="selectSug('<c:out value="${mysug}"/>')"><c:out value="${mysug}"/></label>
<br/>
</c:forEach>
代码
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Multiple values</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#tags")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("ui-autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function(request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
availableTags, extractLast(request.term)));
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tag programming languages: </label>
<input id="tags" size="50" />
</div>
</body>
</html>
谢谢,我会试一试如果我应该继续使用我的sug.jsp文件的代码,应该如何从后端返回列表? – J888 2013-05-14 07:02:13
你可以使用它。但是你产生不必要的流量。更好的选择是JSON回报。 Java中有很多JSON解析器。 – 2013-05-14 07:13:33