原生JS局部刷新

本文介绍了使用JavaScript的XMLHttpRequest对象、fetchAPI以及事件监听器来实现页面的局部刷新。同时,通过一个Servlet示例展示了如何生成和刷新图片验证码,强调了数据格式匹配和跨域问题的重要性。

目录

使用XMLHttpRequest对象进行异步请求:

        2.使用fetch API进行异步请求

      3.使用事件监听器进行局部刷新

       4.servlet实现img验证码局部刷新

依赖jar包

Servlet

login.jsp


在原生JS中,可以使用以下几种方式实现局部刷新:

  1. 使用XMLHttpRequest对象进行异步请求:

// 创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
// 设置请求方式和请求地址
xhr.open('GET', 'example.php', true);
// 发送请求
xhr.send();
// 监听响应状态变化
xhr.onreadystatechange = function() {
  // 响应完成且响应状态为200时,更新页面
  if (xhr.readyState === 4 && xhr.status === 200) {
    var response = xhr.responseText;
    // 更新DOM节点内容
    document.getElementById('result').innerHTML = response;
  }
};

        2.使用fetch API进行异步请求

// 发送GET请求
fetch('example.php')
  .then(function(response) {
    // 将响应解析为文本格式
    return response.text();
  })
  .then(function(data) {
    // 更新DOM节点内容
    document.getElementById('result').innerHTML = data;
  });

      3.使用事件监听器进行局部刷新

// 获取要刷新的DOM节点
var node = document.getElementById('result');
// 添加点击事件监听器
node.addEventListener('click', function() {
  // 发送请求获取更新内容
  fetch('example.php')
    .then(function(response) {
      // 将响应解析为文本格式
      return response.text();
    })
    .then(function(data) {
      // 更新DOM节点内容
      node.innerHTML = data;
    });
});

需要注意的是,使用以上方式进行局部刷新时,需要确保返回的数据格式与页面中要更新的DOM节点类型匹配。另外,使用异步请求时需要注意跨域问题。

       4.servlet实现img验证码局部刷新

依赖jar包

 

Servlet

package com.xzm.view;
import cn.dsna.util.images.ValidateCode;
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;
/**
 * @Description 生成图片验证码
 * @Author XueZhimin
 * @CreateTime 2023-04-03 16:12
 */

@WebServlet("/codeServlet")
public class CodeServlet extends HttpServlet {
    private static ValidateCode validateCode = null;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        validateCode=new ValidateCode(100, 30, 4, 20);
        String code = validateCode.getCode();
        System.out.println(code);
        request.getSession().setAttribute("code",code);
        validateCode.write(response.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
}

login.jsp

<%--
  Created by IntelliJ IDEA.
  User: God_Like
  Date: 2023/4/2
  Time: 16:21
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>

<form action="loginServlet" method="post">


    <table border="1" width="80%" style="margin: auto">

        <tr>
            <th>用户名</th>
            <td>
                <input type="text" name="name" placeholder="请输入用户名">
            </td>
        </tr>

        <tr>
            <th>密码</th>
            <td>
                <input type="password" name="password" placeholder="请输入密码">
            </td>
        </tr>
        <tr>
            <th>
                <img id="code" src="codeServlet" onclick="reFreshCode()">
            </th>

            <td>
                <input type="code" name="code" placeholder="请输入验证码">
            </td>
        </tr>

        <tr>
            <td colspan="2">
                <input style="width: 100%" type="submit" value="登录">
            </td>
        </tr>


    </table>


</form>


<a href="registerServlet">注册</a>
</body>
</html>

<script type="application/javascript">

    //实现验证码局部刷新
    function reFreshCode() {
        // 发送GET请求
        fetch('codeServlet')
            .then(function(response) {
                // 将响应解析为文本格式
                return response.url;
            })
            .then(function(data) {
                // 更新DOM节点内容
                document.getElementById('code').src = data;//DOM操作img标签,更改src
            });
    }

</script>

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寻找优秀的自己

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值