我试图通过从servlet抛出ajax请求和json响应来创建自动完成。但不,不管哪里出错了。 Servlets工作正常。但是来自ajax的请求不会发生。请帮帮我。 提前谢谢..
NewServlet.java
Gson gson = new Gson();
String prefix = request.getParameter("term");
ArrayList<String> matchingSuggestions= suggestions.getAllPrefixMatches(prefix);
//final List<AutoCompleteData> result = new ArrayList<AutoCompleteData>();
for (String suggestion : matchingSuggestions) {
json = gson.toJson(suggestion);
// result.add(new AutoCompleteData(suggestion,suggestion));
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
// response.getWriter().write("<option>"+new Gson().toJson(result)+"<option>"); // Write response body.
response.getWriter().write(json);
}
autocomplete.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript" src="autocompleter.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<div class="search-container">
<div class="ui-widget">
<input type="text" id="search" name="search" class="search" />
</div>
</div>
</body>
</html>
autocompleter.js
$(document).ready(function() {
$(function() {
$("#search").autocomplete({
source : function(request, response) {
$.ajax({
url : "NewServlet",
type : "GET",
data : {
term : request.term
},
dataType : "json",
success : function(data) {
response(data);
}
});
}
});
});
});