<body>
<form action="">
<select id="college" name="college" ></select>
</form>
<script>
var xmlHttp = "";
function getXmlHttpRequest(){
if(window.XMLHttpRequest)
xmlHttp = new XMLHttpRequest();
else
xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
return xmlHttp;
}
function checkName()
{
//获得HttpRequest对象
xmlHttp = getXmlHttpRequest();
//得到url
url="jsonserver.jsp";
//打开请求
xmlHttp.open("get",url,true);
//指定回调函数
xmlHttp.onreadystatechange = getResult;
//向服务器发送请求
xmlHttp.send(null);
}
function getResult()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
//eval 将json格式转化为javascript类型的字符串,但是注意eval可能对本地计算机具有不安全性
var result = eval('('+xmlHttp.responseText+')');
for(var i=0;i<result.length;i++)
{
document.getElementById("college").options.add(new Option(result[i].cname,result[i].vlaue));
}
}
}
document.onreadystatechange = getCollege;//获取列表内容
function getCollege()
{
if(document.readyState == "complete")
checkName();
}
</script>
</body>
</html>
jsonserver.jsp
<%
response.setHeader("Content-Type","text/xml");
response.setHeader("charset","utf-8");
String result ="[{\"value\":0,\"cname\":\"软件学院\"},{\"value\":\"1\",\"cname\":\"计算机学院\"}]";
System.out.println(result);
out.print(result);
out.flush();
%>