如何在xmlhttprequest加入参数以便servlet筛选

来源:2-8 自由编程

慕设计3517557

2019-06-19 16:59:00

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 <button id="btn1">员工列表</button>
 <button id="btn2">职位列表</button>
 <button id="btn3">部门列表</button>
 <div id="container" style="text-align:center"></div>
 <script type="text/javascript" src="js/jquery-3.4.1.js"></script>
 <script type="text/javascript">
  $("#btn1").click(function(){
   //1.创建xmlhttp请求
   var xmlhttp ;
   if (window.XMLHttpRequest){
    xmlhttp = new XMLHttpRequest();
   } else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
   }
   //2.发送请求
   xmlhttp.open("GET","/ajax/twoeight",true);
   xmlhttp.send();
   //3.处理服务器响应
   xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200 ){
     var text = xmlhttp.responseText ;
     var json = JSON.parse(text) ;
     var temp = "" ;
     for (var i = 0 ; i< json.length ; i ++ ){
      temp = temp + "<h1>" + json[i] + "</h1>" ;
     }
     $("#container").html(temp);
    }
   }
  });
 </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 twoeight
 */
@WebServlet("/twoeight")
public class twoeight extends HttpServlet {
 private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public twoeight() {
        super();
        // TODO Auto-generated constructor stub
    }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  List listone = new ArrayList();
  listone.add("小张");
  listone.add("小明");
  listone.add("小李");
  String lone = JSON.toJSONString(listone);
  List listtwo = new ArrayList();
  listtwo.add("职员");
  listtwo.add("经理");
  String ltwo = JSON.toJSONString(listtwo);
  List listthree = new ArrayList();
  listthree.add("人事部");
  listthree.add("技术部");
  listthree.add("无线事业部");
  String lthree = JSON.toJSONString(listthree) ;
  response.setContentType("text/html;charset=UTF-8");
  response.getWriter().println(lone);
 }

}


写回答

1回答

好帮手慕柯南

2019-06-19

同学你好!可以参考一下这个已采纳的回答里的例子来完成

https://class.imooc.com/course/qadetail/100137

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

0

0 学习 · 10204 问题

查看课程