帮看下: 为什么页面不显示列表,后台console乱码

来源:2-8 自由编程

Longhaier

2019-04-28 17:10:35

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
  <style>
  	#container{
  	text-align:center;
  	height: 600px;
  	}
    .btn {
      width:30%;
    }
  </style> 

</head>
<body>
	<div>
		<button id="btn1" class="btn" onclick="check(1)" >员工列表</button>
		<button id="btn1" class="btn" onclick="check(2)">职位列表</button>
		<button id="btn1" class="btn" onclick="check(3)">部门列表</button>
	</div>
	<div id="container"></div>
	
	<script>
		//1,创建XmlHttpRquest对象
		var xmlhttp;
		if(window.XMLHttpRequest){
			xmlhttp = new XMLHttpRequest();
		}else{
			xmlhttp=new ActiveObject("Microsoft.XMLHTTP");
		}
		
		function check(flag){
			//2,发送ajax请求
			xmlhttp.open("get","http://localhost:8080/Company/list?flag="+flag,true);
			xmlhttp.send();
			//3,处理服务器响应
			xmlhttp.onreadystatechange= function(){
				if(xmlhttp.readyState==4 && xmlhttp.status==200){
					var text = xmlhttp.responseText;
					var json=JSON.parse(text);
					console.log(json);
					html="";
					for (var i=0; i<json.length;i++){
						var emp = json[i];
						html=html+"<h2>"+emp+"</h2>";
						html=html+"<br>"
					}
					document.getElementById("container").innerHTML(html);
					
				}
			}
		}
		
	</script>
</body>
</html>


servlet:

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 ListServlet
 */
@WebServlet("/list")
public class ListServlet extends HttpServlet {
	

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		List<String> dep = new ArrayList();
		List<String> emp = new ArrayList();
		List<String> pos = new ArrayList();
		
		dep.add("人事部");
		dep.add("市场部");
		dep.add("研发部");
		
		emp.add("张三丰");
		emp.add("杨过");
		emp.add("黄老邪");
		
		pos.add("工程师");
		pos.add("经理");
		pos.add("董事长");
		
		response.setContentType("text/html;charset:UTF-8");
		int flag = Integer.parseInt(request.getParameter("flag"));
		switch(flag) {
		case 1:{
			String json = JSON.toJSONString(emp);
			response.getWriter().println(json);
			break;
		}
		case 2:{
			String json = JSON.toJSONString(dep);
			response.getWriter().println(json);
			break;
		}
		case 3:{
			String json = JSON.toJSONString(pos);
			response.getWriter().println(json);
			break;
		}
		}
		}
}


谢谢: )

写回答

1回答

好帮手慕柯南

2019-04-28

同学你好!

  1. 乱码问题,在代码中添加响应的编码格式

    http://img.mukewang.com/climg/5cc57c8e00019c2c07670170.jpg

  2. 不显示列表问题,同学显示列表时写错了呢,要用等于号

    http://img.mukewang.com/climg/5cc57cdc0001cd5d08280115.jpg

如果我的回答解决了你的疑惑,请采纳,祝学习愉快~

1

0 学习 · 10204 问题

查看课程