我使用SQL表作比较并在input
字段主题上生成了一个自动完成下拉菜单。
它确实起作用,尽管现在我想添加也使用input
但在不同表上的其他autocomplete
字段,而不必创建多个servlet。
因此,我创建了一个字段input_name
,该字段从input
字段主题onkeyup
到put_input(id)
的ID中获取值。我没有把它放在这里,因为它很好用。
所以现在我正尝试将input_name
的值发送到我的Servlet,以便可以将其与“ subject”之类的字符串进行比较,并确定要使用哪个表。
但是,它总是返回stored.table_0
,这意味着request.getParameter("input_name2")
为null,即使我在HTML端可以看到input_name的正确值。
index.html
$(function (){
$("#subject").autocomplete({
source: "Servlet",
minLength: 1
});
});
$(document).ready(function(){
$("#subject").keyup(function(){
var input_name = $("#input_name").val();
$.ajax({
type: "POST",
source: "Servlet",
data: {input_name2: input_name}
});
});
}); </script> <html> ...
<input type="text" id="input_name" name="input_name">
<input type="text" id="subject" onclick="put_input(id)">
Servlet.java代码段
try { response.setContentType("text/html;charset=UTF-8");
response.setContentType("application/json");
StoredData stored = new StoredData();
String table = "";
String input_name = request.getParameter("input_name2");
if (input_name == null) {
table = stored.table_0;
}
if ("subject".equals(input_name)) {
table = stored.table_subject;
}
String term = request.getParameter("term");
GetSQL sql = new GetSQL();
String json = new Gson().toJson(GetSQL.showOptions(term, table));
response.getWriter().write(json);
} catch (Exception e){
System.out.println(e.getMessage());}
我经常使用我的代码,在ajax中添加了contentType
,这是一个不必要的功能,尝试使用$.post
方法,以此类推,等等,但是实际上什么也没做。但是,当我尝试通过HTML上的JSP发布input_name
时,它的效果很好,并且将input_name
打印到HTML上(如果其值为主题)。像这样:
添加到index.html
$("#subject").keyup(function(){
var input_name = $("#input_name").val();
$.post( "index2.jsp", {input_name2: input_name}, function(data){
$("#msg").html(data);
});
}); </script>
<html> ...
<div id="msg" name="msg"></div>
index2.jsp
<%
String input_name = request.getParameter("input_name2");
if ("subject".equals(input_name)){
out.println(input_name);
}
%>
这是我第一次使用ajax,我只是不知道如何解决它。在谷歌上搜索仅使我到此为止。人们经常尝试发送JSON,但我只想在Servlet上获取一个简单的字符串... 预先感谢!
编辑:可悲的是,链接的答案仍然无法帮助我解决它。我没有在{ input_name2 : input_name }
声明data
,而是尝试在ajax调用之前声明它,然后继续对$.param(new_input_name)
使用data
。仍然为空。