json.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>form.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<select id="province" name="province">
<option value="">请选择....</option>
</select>
<select id="city" name="city">
<option value="">请选择.....</option>
</select>
</body>
<script language="JavaScript">
window.onload = function(){
var xhr = ajaxFunction();
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
if(xhr.status==200){
var data = xhr.responseText;
/*
* 利用eval()函数:将数据转换成符合JSON格式
* * 如果向eval()函数,传递一对空的大括号"{}"(表示一个空的JSON格式的数据内容)
* * 利用"()"将其包装,eval()函数会强行将其转换成JSON格式.
* * 不用"()"将其包装,eval()函数会将其解释为一个空的语句块
*/
var json = eval("("+data+")");
//alert(json);
console.info(json);
// for(var i=0;i<json.length;i++){
// var provinceValue = json[i].province;
//
// //<option value="">请选择....</option>
// var option = document.createElement("option");
// option.setAttribute("value",provinceValue);
// var text = document.createTextNode(provinceValue);
// option.appendChild(text);
//
// var provinceElement = document.getElementById("province");
//
// provinceElement.appendChild(option);
// }
}
}
}
xhr.open("get","../jsonServlet?timeStamp="+new Date().getTime(),true);
xhr.send(null);
function ajaxFunction(){
var xmlHttp;
try{ // Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e){
try{// Internet Explorer
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
return xmlHttp;
}
}
</script>
</html>
JsonServlet.java
package app.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JsonServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//如果服务器端向客户端响应数据格式为JSON时,不需要设置响应首部信息
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
/*
* * 查询数据库:
* * 结果集为JavaBean
* * 结果集为集合
* * 模拟查询数据库:手工方式构建
*/
//手工方式构建:String类型的符合JSON数据格式的数据内容
String json = "[{'province':'吉林省'},{'province':'辽宁省'},{'province':'山东省'}]";
out.println(json);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}