要实现提交表单不跳转页面,可以使用 Ajax 技术。以下是使用 jQuery 的示例代码:

<!DOCTYPE html>
<html>
<head>
    <title>提交表单不跳转页面</title>
    <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
</head>
<body>

<form id='myForm'>
    <input type='text' name='name' placeholder='姓名'><br>
    <input type='email' name='email' placeholder='邮箱'><br>
    <input type='submit' value='提交'>
</form>

<script>
$(document).ready(function(){
    // 监听表单的提交事件
    $('#myForm').submit(function(e){
        e.preventDefault(); // 阻止表单默认的提交行为

        // 使用Ajax发送表单数据到服务器
        $.ajax({
            url: 'process.php', // 提交到的后台处理页面
            type: 'POST', // 请求方法
            data: $(this).serialize(), // 表单数据
            success: function(response){
                // 处理服务器返回的响应数据
                console.log(response);
            }
        });
    });
});
</script>

</body>
</html>

上述代码中,#myForm代表表单的 id,通过 submit() 方法监听表单的提交事件。当用户点击提交按钮时,会调用回调函数中的代码。

在回调函数中,首先调用 e.preventDefault() 方法阻止表单默认的提交行为。然后使用 $.ajax() 方法发送 Ajax 请求,将表单数据通过 $(this).serialize() 方法序列化为字符串,并提交到 process.php 页面进行处理。

process.php 页面中,可以使用 PHP 代码获取表单数据,并进行相应的处理。处理完毕后,可以通过 echoprint 等方式返回响应数据。

这样就实现了提交表单不跳转页面的效果。


原文地址: https://www.cveoy.top/t/topic/pg2b 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录