2-8 自由编程
来源:2-8 自由编程
慕的地2082093
2020-02-06 15:37:58
package json;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
/**
* Servlet implementation class companyServlet
*/
@WebServlet("/aj")
public class companyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public companyServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
List list=new ArrayList();
list.add("小红<br>小明<br>小白");
list.add("职员<br>经理");
list.add("人事部<br>技术部<br>无线事业部");
String json=JSON.toJSONString(list);
response.setContentType("text/html;charset=UTF-8");
response.getWriter().println(json);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>职员列表</title>
<style type="text/css">
input{
width:300px;
}
</style>
</head>
<body>
<div style='padding-left:25%'>
<input type="button" value="员工类表" name="in">
<input type="button" value="职位类表" name="in">
<input type="button" value="部门类表" name="in">
</div>
<div id="content" style='text-align:center'>111</div>
</body>
<script type="text/javascript">
var input=document.getElementsByName("in");
for(var i=0;i<input.length;i++){
input[i].setAttribute("index",i);
input[i].onclick=function(){
var idx=this.getAttribute("index");
//1.创建xmlHpptRequest
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
//xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//2.发送Ajax请求
xmlhttp.open("GET","/json/aj",true);
xmlhttp.send();
//3.处理服务器响应
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 &&xmlhttp.status == 200 ){
var text=xmlhttp.responseText;
var json=JSON.parse(text);
document.getElementById("content").innerHTML = json[idx];
}
}
}
}
</script>
</html>
老师,帮看下代码对吗?还有个问题为什么删除response.getWriter().println(json);浏览器点击响应不会显示内容,这行语句document.getElementById("content").innerHTML = json[idx];不是把json[i]中得内容放回到id为content的div中吗?
1回答
好帮手慕酷酷
2020-02-06
同学你好,代码完成的不错,实现了效果功能,老师这里回答一下同学的问题:
1、为什么删除response.getWriter().println(json);浏览器点击响应不会显示内容,这行语句document.getElementById("content").innerHTML = json[idx];不是把json[i]中得内容放回到id为content的div中吗?
这里response.getWriter().println(json);表示将获取的json数据,返回给ajax调用处,进行处理服务器响应。document.getElementById("content").innerHTML = json[idx];是将json[i]中得内容放回到id为content的div中,但是companyServlet类需要将获取到的json数据进行返回,才可以得到json[i],放入div中。
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
相似问题