在下面,我们在下拉列表中填充名称,一旦下拉值更改,我们需要在文本框中打印相应的名字、姓氏、地址、登录名。这是我们需要实现的
这是我的jsp代码。
<% DBConnection dbc=new DBConnection();
Connection con=dbc.getNewConnection();
Statement st = null;
ResultSet rs = null;
try
{
st=con.createStatement() ;
rs=st.executeQuery("select * from Users");
%>
<select id="selectBox" >
<% while(rs.next()){ %>
<option><%= rs.getString(2)%></option>
<%} %>
</select>
<input id="loginid" type="text" value="" />
<input id="firstname" type="text" value="" />
<input id="lastname" type="text" value="" />
<input id="address" type="text" value="" />
那么如何根据从用户表中选择的名称填充以上 4 个值。
请帮助我如何编写 Javascript 函数来做到这一点。
您首先需要编写onchange
事件处理程序,以便在选择框值获取更改时,this
处理程序将被调用,然后将值发送select
到后端页面(servlet).so,ajax代码将如下所示:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$('select#selectBox').on('change', function() {
var value = $(this).val(); //get value from select-box
$.ajax({
type: 'POST',//can be post request or get
url: url,//put url here where you need to send
data: {
'value': value//pass value
},
success: function(response) {
//result will come here
//if recieve as html use
$("somedivclass").html(response)
//if recieve as separted commas
var result = response.split(",")
//access same using result[0],result[1] ..etc
//add value to input using
$("#loginid").val(result[0]);
//same for other
}
});
})
在您的服务器端,如果发出请求,则使用 ajax 的request.getParameter("value")
内部doPost
方法获取从 ajax 传递的值。然后POST
,只需编写您的查询以从 db 检索记录并将其发送回 ajax。因此,您的代码将如下所示:
String value = (String) request.getParameter("value");
String query = "select * from Users where yourcolumnanemtocompare=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, value);
ResultSet rs = ps.executeQuery();
//if value there
String text;
if (rs.next()) {
//change value accordingly..i.e : rs.getstring..
text = "<input id=" + loginid " type="
text " value=" + rs.getInt(1) + " /><input id="
firstname " type="
text " value=" + rs.getInt(2) + " /> <input id="
lastname " type="
text " value=" + rs.getInt(3) + " /><input id="
address " type="
text " value=" + rs.getInt(4) + " />";
}
response.setContentType("text/html"); // Set content type
response.setCharacterEncoding("UTF-8");
response.getWriter().write(text); // response to send back.
//or
if (rs.next()) {
//change value accordingly..i.e : rs.getstring..
text = rs.getInt(1) + "," + rs.getInt(2) + "," + rs.getInt(3) + "," + rs.getInt(4);
}
response.setContentType("text/plain"); // Set content type
response.setCharacterEncoding("UTF-8");
response.getWriter().write(text); // response to send back..
//or use json to send data..
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句