前端页面代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajax get请求</title> <script type="text/javascript"> window.onload = function () { document.getElementById("btn").onclick = function () { //获取页面中用户动态输入的信息 var userName = document.getElementById("userName").value; var pwd = document.getElementById("pwd").value; //发送ajax get请求 //1.创建XMLHttpRequest对象 var xhr = new XMLHttpRequest(); //2.注册回调函数 xhr.onreadystatechange = function () { if (xhr.readyState == 4) { //也可以写成:this.readyState == 4 if (xhr.status == 200) { //还可以写成:this.status == 200 document.getElementById("myDiv").innerHTML = xhr.responseText; }else { alert(xhr.status); } } }; //3.打开通道 //get请求提交数据是在“请求行”上提交,写在url中 xhr.open("GET","/ajax/request2?userName="+ userName +"&pwd="+ pwd,true); //4.发送请求 xhr.send(); } } </script> </head> <body bgcolor="#fff8dc"> 用户名:<input type="text" id="userName"/><br/> 密码:<input type="password" id="pwd"/><br/> <button id="btn">发送ajax get请求</button> <div id="myDiv"></div> </body> </html>
服务端代码:
package com.yjg.ajax.servlet; 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 java.io.IOException; import java.io.PrintWriter; @WebServlet("/request2") public class AjaxRequest2Servlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取前端信息 String userName = request.getParameter("userName"); String pwd = request.getParameter("pwd"); //设置响应内容的类型和字符集 response.setContentType("text/html;charset=UTF-8"); //获取输出流 PrintWriter out = response.getWriter(); //输出响应内容 out.print("<font color = 'red'>用户名:"+ userName +";密码:"+ pwd +" </font>"); } }
程序运行之后浏览器页面显示: