避免在 servlet 中重新加载页面

问题描述 投票:0回答:1

我构建了一个 profile.jsp,其中有 emailPopupotpPopup。 当我在 emailPopup 中输入电子邮件时,电子邮件将发送到 servlet 并重定向回 profile.jsp。重新加载后,我应该再次打开emailPopUp,因为按钮otpPopup出现在emailPopup中。

我怎样才能避免页面重新加载来解决这个问题...... 请帮我解决这个问题

我不知道该怎么办。完全没有想法

javascript java jsp servlets reload
1个回答
0
投票

您可以在 JavaScript 中使用 event.preventDefault() 。一旦考虑一下由 chatgpt 生成的示例代码。

<!-- Your form in profile.jsp -->
<form id="emailForm" action="/your-servlet-endpoint" method="post">
    <!-- Your form fields go here -->
    <input type="email" name="email" required>
    <button type="submit" id="submitEmail">Submit Email</button>
</form>

<script>
document.addEventListener('DOMContentLoaded', function() {
    var emailForm = document.getElementById('emailForm');

    emailForm.addEventListener('submit', function(event) {
        // Prevent the default form submission behavior
        event.preventDefault();

        // Now you can perform any additional actions you need, such as AJAX request to the servlet
        // Example using Fetch API
        fetch('/your-servlet-endpoint', {
            method: 'POST',
            body: new FormData(emailForm),
            // Additional options as needed
        })
        .then(response => {
            // Handle the response as needed
            // For example, open the OTP popup
            openOTPPopup();
        })
        .catch(error => {
            // Handle errors
            console.error('Error submitting form:', error);
        });
    });

    function openOTPPopup() {
        // Add your logic to open the OTP popup here
    }
});
</script>

© www.soinside.com 2019 - 2024. All rights reserved.