【发布时间】:2014-01-03 06:34:52
【问题描述】:
我有一个Jsp页面,表单包含两个下拉列表,第一个显示国家名称,第二个显示相应国家下的状态。我的Mysql数据库分别包含两个表国家和州。我需要使用 Ajax 从数据库中填充两个下拉列表,其中数据库中的数据必须转换为 Json 对象并作为 Json 对象提供响应。然后根据此响应 Json 对象填充两个下拉列表。不使用任何 php或 .net 代码在这里。给我一些示例代码,在 Jsp 中使用 Ajax 执行此操作。下面是我到目前为止所做的代码。但是这里第二个下拉列表没有被填充。
国家.jsp
<%@page import="java.sql.*"%>
<html>
<head>
<script language="javascript" type="text/javascript">
var xmlHttp;
function showState(str){
if (typeof XMLHttpRequest != "undefined"){
xmlHttp= new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp==null){
alert("Browser does not support XMLHTTP Request");
return;
}
var url="state.jsp";
url +="?count=" +str;
xmlHttp.onreadystatechange = stateChange;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function stateChange(){
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
var myJson=new JSONObject(xmlHttp.responseText);
console.log($(this).val());
$("#state").empty();
$("#state").append('<option value="-1">-Select State-</option>');
$.each(myJson.arrayName, function (index, value) {
$("#state").append('<option value="'+value.id+'">'+value.name+'</option>');
});
}
}
</script>
</head>
<body>
<select name='country' onchange="showState(this.value)">
<option value="none">Select</option>
<%ResultSet rs=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:
3306/test","root","root");
Statement stmt = con.createStatement();
rs = stmt.executeQuery("Select * from country");
while(rs.next()){
%>
<option value="<%=rs.getString(1)%>"><%=rs.getString(2)%></option>
<%
}}catch(Exception e){
}
%>
</select>
<br>
<div id='sta'>
<select id='state' name='statess' >
<option value='-1'>select</option>
</select>
</div>
</body>
</html>
state.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<%@page import="java.util.*,java.util.ArrayList"%>
<%@page import="net.sf.json.JSONObject"%>
<%@page import="net.sf.json.JSONArray"%>
<%
JSONArray cellarray = new JSONArray();
JSONObject cellobj = null; //new JSONObject();
JSONObject jo=new JSONObject();
String country=request.getParameter("count");
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:
3306/test","root","root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("Select * from
state where countryid='"+country+"'");
while(rs.next()){
cellobj = new JSONObject();
cellobj.put("id", rs.getString(1));
cellobj.put("name", rs.getString(3));
cellarray.add(cellobj);
}
jo.put("arrayName",cellarray);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jo.toString());
}
catch(Exception e){
System.out.println(e);
}
%>
【问题讨论】:
-
同样的问题在 2 小时内stackoverflow.com/q/20896782/1031945
-
上面的代码可以运行,但是我需要将响应数据替换为json格式并在代码中进行必要的修改