2-8自由编程
来源:2-8 自由编程
RobinZang
2019-10-01 15:14:09
package com.imooc.ajax; 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 EmployeeListServlet */ @WebServlet("/employee_list") public class EmployeeListServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public EmployeeListServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<String> list = new ArrayList<String>(); list.add("小红<br>小明<br>小白<br>"); list.add("职员<br>经理<br>"); list.add("人事部<br>技术部<br>无线事业部"); String json = JSON.toJSONString(list); System.out.println(json); response.setContentType("text/html;charset=UTF-8"); response.getWriter().println(json); } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>职员列表</title> </head> <body> <input id="btnLoad1" type="button" value="员工列表"> <input id="btnLoad2" type="button" value="职位列表"> <input id="btnLoad3" type="button" value="部门列表"> <div id="divContent"></div> <script> //1.创建XmlHttpRequest var xmlhttp; if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } //2.发送Ajax请求 xmlhttp.open("GET", "/ajax/employee_list", 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("btnLoad1").onclick = function() { document.getElementById("divContent").innerHTML = "<p style='text-align:center'>"+json[0]+"</p>"; }; document.getElementById("btnLoad2").onclick = function() { document.getElementById("divContent").innerHTML = "<p style='text-align:center'>"+json[1]+"</p>"; }; document.getElementById("btnLoad3").onclick = function() { document.getElementById("divContent").innerHTML = "<p style='text-align:center'>"+json[2]+"</p>"; }; } }; </script> </body> </html>
1回答
好帮手慕阿莹
2019-10-06
实现了作业要求,做的不错哦,继续加油!
如果我的回答解决了你的疑问,请采纳,祝学习愉快。
相似问题