老师帮忙看看我这个怎么样,顺便置个顶吧!
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;
import jdk.nashorn.internal.runtime.JSONFunctions;
/**
* Servlet implementation class AjaxJson
*/
@WebServlet("/aj")
public class AjaxJson extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AjaxJson() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String y="小红<br>小明<br>小白<br>";//要加多少个,自己看着加
String z="职员<br>经理<br>";
String b="人事部<br>技术部<br>无线事业部";
List list=new ArrayList();
list.add(y);
list.add(z);
list.add(b);
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>Insert title here</title>
</head>
<body>
<input type="button" value="员工列表" name="in">
<input type="button" value="职位列表" name="in">
<input type="button" value="部门列表" name="in">
<div style='text-align:center' id="divContent"></div>
<script type="text/javascript">
//取出数组
var input=document.getElementsByName("in");
//遍历数组
for(var i=0;i<input.length;i++){
//给每个按钮加个索引属性,要不每个按钮都是显示最后的值,这个在轮播图那里有教过
input[i].setAttribute("data-index",i);
//给每个按钮加单击事件
input[i].onclick=function(){
//1
var idx=this.getAttribute("data-index");
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//2
xmlhttp.open("GET","/ServletProj/aj",true);
xmlhttp.send();
//3
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
var json=JSON.parse(xmlhttp.responseText);
//每个按钮索引对应每个json索引
document.getElementById("divContent").innerHTML=json[idx];
}
}
}
}
</script>
</body>
</html>按钮样式我懒得弄了,有没有需要改进的地方,或者可以更简单点,我看其他同学编的都多多少少有点小毛病,不够完美。
309
收起
正在回答
1回答
同学你好!
完成的不错,看到同学使用了之前学习过的知识,给你点赞,这种学以致用的学习态度和方法很棒。
可以帮同学置顶,以便帮助更多的同学~ 加油!!!
祝学习愉快~
2. 从网页搭建入门JavaWeb
- 参与学习 人
- 提交作业 676 份
- 解答问题 9666 个
本阶段将从前端网页搭建入手,到Java Web基础,前后端结合助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星