使用JQyery的Ajax请求(GET方式)包含web.xml设置

2022/5/28 23:20:04

本文主要是介绍使用JQyery的Ajax请求(GET方式)包含web.xml设置,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

******html代码******

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>测试</title>
    <script src="lib/jquery-3.6.0.js"></script>
</head>
<body>
    <h1 id="cc">js</h1>
    <h2 id="dd">js1</h2>
    <div id="a">js2</div>
    <button id="b" >点我</button>
<script>
    $(function (){
        $("#b").click(function () {
            let xhr = new XMLHttpRequest();
            xhr.onreadystatechange=function (){
                if (xhr.readyState==4){
                    if(xhr.status==200) {
                        $("#dd").html("<h1>123</h1>")
                        document.getElementById("a").innerHTML=this.responseText;
                    }
                }
            }
            xhr.open("GET","ajaxServlet01",true)
            xhr.send();
        })
    })
</script>

</body>
</html>

******java代码******
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("/ajaxServlet01")
public class ajaxServlet01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("11111111111111111111111");
        PrintWriter out = resp.getWriter();
        out.print("<h1>1111111111111111</h1>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

******web.xml设置******
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0"
         metadata-complete="false">

  <display-name>Welcome to Tomcat</display-name>
  <description>
    Welcome to Tomcat
  </description>
  <!--注册servlet-->
  <servlet>
    <servlet-name>com.liu.servlet.com.liu.listener.hello</servlet-name>
    <servlet-class>se</servlet-class>
  </servlet>
  <!--注册servlet请求路径-->
  <servlet-mapping>
    <servlet-name>com.liu.servlet.com.liu.listener.hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>

</web-app>


1、这里的web.xml必须将metadata-complete="false",不然无法使用注解
2、需要导入jQuery包jquery-3.6.0.js
本人经过反复多次测试总结出的小小经验,希望能够帮助大家~~~


这篇关于使用JQyery的Ajax请求(GET方式)包含web.xml设置的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程