麻烦老师看一下我这个哪里错了
我就这两个文件来处理,但无响应,是哪里错了呀,这个思路可行吗
<%@ page language="java" contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>这是职员列表</title>
</head>
<body>
<div style="width:1000px;">
<button style="width:300px;">员工列表</button>
<button style="width:300px;">职位列表</button>
<button style="width:300px;">部门列表</button>
</div>
<div id="outstr" style="width:1000px;text-align:center;">
<!-- 此处输出ajax返回的内容 -->
</div>
<script type="text/javascript">
//获得三个按钮button的数组bList
var bList=document.getElementsByTagName("button");
var outstr=document.getElementById("outstr");
for(var i=0;i<bList.length;i++){
bList[i].onclick=function(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var url="/ajax/emp_servlet?num=";
url=url+i;
xmlhttp.open("GET",url,true);
url="";
xmlhttp.send();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
var t = xmlhttp.responseText;
document.getElementById("outstr").innerHTML=t;
}
}
}
}
</script>
</body>
</html>
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;
/**
* Servlet implementation class empListServlet
*/
@WebServlet("/emp_servlet")
public class empListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public empListServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String i=request.getParameter("num");
List<String> list=new ArrayList<String>();
if(i.equals("0")) {
list.add("小红");
list.add("小明");
list.add("小白");
}else if(i.equals("1")) {
list.add("职员");
list.add("经理");
}else {
list.add("人事部");
list.add("技术部");
list.add("无线支持部");
}
String outstr="";
for(var str:list) {
outstr+="<h3>"+str+"</h3>";
}
response.getWriter().println(outstr);
}
}
正在回答
同学你好,
因为在for循环里面指定给bList[i].onclick的事件处理程序,也就是onclick那个匿名函数是在for循环执行完成后(用户点击时)才被调用的,function中的i永远是3,也就是for循环遍历后的i值
我们可以在外边设置一个变量赋值一下,如下图所示:

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
- 参与学习 人
- 提交作业 9410 份
- 解答问题 16556 个
综合就业常年第一,编程排行常年霸榜,无需脱产即可学习,北上广深月薪过万 无论你是未就业的学生还是想转行的在职人员,不需要基础,只要你有梦想,想高薪
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星