点击各按钮无结果,并且在页面报错
来源:2-8 自由编程
qq_cookies_oqrHNO
2019-04-09 12:00:02
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table width="100%">
<tr>
<td width="33%"><button id="y" style="width:100%;">员工列表</button></td>
<td width="33%"><button id="z" style="width:100%;" >职位列表</button></td>
<td width="33%"><button id="b" style="width:100%;">部门列表</button></td>
</tr>
</table>
<div id="content" style="text-align: center;"></div>
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
//1.创建ajax对象
var xmlhttp;
if(window.XMLHttpRequest){
xml=new XMLHttpRequest();
}else{
xmlhttp=new ActiveObject("Microsoft.XMLHTTP");
}
$("#y,#b,#z").click(function(){
var url = "/ajax_practice/content?id=" + this.id;
//2.发送ajax请求
xmlhttp.open("GET",url,true);
xmlhttp.send();
//3.处理服务器响应
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
var t=xmlhttp.responseText;
var json=JSON.parse(t);
var html="";
for(var i=0;i<json.length;i++){
html=html+json[i];
html=html+"<hr>";
}
document.getElementById("content").innerHTML=html;
}
}
});
</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;
import com.alibaba.fastjson.JSON;
/**
* Servlet implementation class ContentServlet
*/
@WebServlet("/content")
public class ContentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ContentServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List yList=new ArrayList();
List bList=new ArrayList();
List zList=new ArrayList();
yList.add("小红");
yList.add("小明");
yList.add("小白");
bList.add("人事部");
bList.add("技术部");
bList.add("无线事业部");
zList.add("职员");
zList.add("经理");
String jsony=JSON.toJSONString(yList);
String jsonb=JSON.toJSONString(bList);
String jsonz=JSON.toJSONString(zList);
response.setContentType("text/html;charset=UTF-8");
if( request.getParameter("id").equals("y") ) {
System.out.println(jsony);
response.getWriter().println(jsony);
}else if( request.getParameter("id").equals("b") ) {
System.out.println(jsonb);
response.getWriter().println(jsonb);
}else if( request.getParameter("id").equals("z")) {
System.out.println(jsonz);
response.getWriter().println(jsonz);
}
}
}
2回答
同学你好。这里同学笔误了哦。应该是xmlhttp。因为同学的使用的浏览器走的是第一种创建方式,所以这里创建出的是变量xml,xmlhttp并没有被创建,所以使用对应方法会被认为undefined:
如果解答了同学的疑问,望采纳~
祝学习愉快~
芝芝兰兰
2019-04-09
同学你好。代码这里拼入了HTML的水平分割线<hr>,去掉这句就不会有了哦:
祝学习愉快~
相似问题