Ajax入门-异步通信-服务器返回数据

实现描述

在index.jsp页面,点击按钮,执行JavaScript代码,与servlet建立异步通信,然后servlet返回一个具体的参数,在index.jsp页面会有弹出框,提示servlet返回的内容

代码

  • index.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>test</title>
		<script type="text/javascript">
		/*全局变量*/
		var xmlHttp;

		/*创建异步对象*/
		function createXMLHttpRequest() {
		    /*IE浏览器*/
		    if (window.ActiveXObject){
		        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		    }
		    /*其他浏览器*/
		    else if (window.XMLHttpRequest){
		        xmlHttp = new XMLHttpRequest();
		    }
		}

		function startRequest() {
		    console.log("startRequest");
		    createXMLHttpRequest();
		    xmlHttp.open("GET","http://localhost:8080//Ajax入门//return",true);
		    xmlHttp.onreadystatechange = function () {
		        if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
		            alert("服务器返回:" + xmlHttp.responseText);
		        }
		    }
			xmlHttp.send(null);
		}		
		</script>
	</head>
	<body>
		<input type="button" value="测试异步通信" onclick="startRequest();">
	</body>
</html>
  • servlet
package myServlet;

import java.io.IOException;
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 ReturnServlet
 */
@WebServlet("/ReturnServlet")
public class ReturnServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ReturnServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		/*write函数里的参数-->返回的数据*/
		response.getWriter().write("测试异步通信成功");
	}
}
  • web.xml
    url-pattern的设置,对应JavaScript中 建立请求的代码:xmlHttp.open(“GET”,“http://localhost:8080//Ajax入门//return”,true);
    即“http://localhost:8080//Ajax入门//return”改成“http://localhost:本地端口号//项目名//url-pattern
	<servlet>
		<servlet-name>自定义的servlet类名</servlet-name>
		<servlet-class>包名.自定义的servlet类名</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>自定义的servlet类名</servlet-name>
		<url-pattern>/自定义的路径</url-pattern>
	</servlet-mapping>

大四了,还没仔细了解过Ajax,汗颜😓😓

©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页