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