0
我正在嘗試在我的web應用程序中實現自動完成功能。數據從我的服務器加載到自動完成功能。我使用Jquery AutoComplete
爲了這個目的 - http://jqueryui.com/autocomplete/#remote-jsonp如何從JQuery Auto獲取正確的數據完成多個數據發送?
下面是我的jQuery代碼
$(document).ready(function() {
$(function() {
$("#addDrugTxt").autocomplete({
source: function(request, response) {
$.ajax({
url: "Autocomplete",
type: "POST",
data: { term: request.term },
dataType: "json",
success: function(data) {
response(data);
}
});
},
minLength: 2,
select: function(event, ui) {
log("Selected: " + ui.item.label);
}
});
$("#addDrugTxt").autocomplete("option", "appendTo", ".form-horizontal");
});
});
function log(message) {
document.getElementById("brandTxt").value = message;
alert("damn");
}
下面是我的Java代碼,將數據提供給jQuery代碼。
public class Autocomplete extends HttpServlet {
private final List<String> drugList = new ArrayList<String>();
int idUser=0;
@Override
public void init()
{
}
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
idUser=Integer.parseInt(request.getSession(false).getAttribute("UserID").toString());
try {
drugList.clear();
DrugNamesTable table = new DrugNamesTable();
List<DrugNamesBean> drugNames = table.getDrugNames(idUser);
System.out.println("Drug names taken");
// Map real data into JSON
response.setContentType("application/json");
final String param = request.getParameter("term");
final List<AutoCompleteData> result = new ArrayList<AutoCompleteData>();
for (final DrugNamesBean data: drugNames) {
if (data.getDrugName().toLowerCase().startsWith(param.toLowerCase())) {
result.add(new AutoCompleteData(String.valueOf(data.getIdDrugName()), data.getDrugName()));
}
}
response.getWriter().write(new Gson().toJson(result));
} finally {
out.close();
}
}
}
在上面的Java代碼中,我使用了一個名爲AutoCompleteData
的bean。它的代碼如下。
public class AutoCompleteData {
private final String label;
private final String value;
public AutoCompleteData(String _label, String _value) {
super();
this.label = _label;
this.value = _value;
}
public final String getLabel() {
return this.label;
}
public final String getValue() {
return this.value;
}
}
但是我要的是顯示AutoCompleteData._value
時自動完成建議都上來了。不幸的是,我得到的都是AutoCompleteData._label
。
當然AutoCompleteData._label
對我很重要,因爲我還需要動態更改addDrugTxt
的id
。
我該如何解決這個問題?
你能提供的HTML代碼,以及 – Abhijeet