1. 主页
  2. 文档
  3. Ajax
  4. js阻止表单提交事件

js阻止表单提交事件

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form id="login" action="https://www.imooc.com/api/http/search/suggest?words=js" method="POST" enctype="multipart/form-data">
        <input type="text" name="username" id="user" value="" />
        <input type="password" name="pass" id="pass" value="" />
        <input type="submit" name="submit" id="submit" value="登陆">
    </form>
    <script>
        var fm = document.getElementById("formgi");
        var us = document.getElementById("user");
        var ps = document.getElementById("pass");
        var su = document.getElementById("submit");


        //阻止表单提交
        //AJAX提交

        su.onclick = function(e) {
            e.preventDefault();

            var xhr = new XMLHttpRequest();
            const url = 'https://www.imooc.com/api/http/search/suggest?words=js';

            xhr.onreadystatechange = function() {
                if (xhr.readyState != 4) return;
                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
                    console.log(xhr.response);
                }
            };

            var usn = us.value;
            var pass = ps.value;

            var data = `username=${usn}&pass=${pass}`;
            xhr.open('POST', url, true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send(data);
        }
    </script>
</body>

</html>




Request URL: http://www.xx.com/25.html
Request Method: POST
Status Code: 200 OK
Remote Address: 127.0.0.1:80
Referrer Policy: no-referrer-when-downgrade
Accept-Ranges: bytes
Connection: Keep-Alive
Content-Length: 2738
Content-Type: text/html
Date: Sat, 05 Feb 2022 16:23:35 GMT
ETag: "ab2-5d747c9f1e816"
Keep-Alive: timeout=5, max=100
Last-Modified: Sat, 05 Feb 2022 16:23:34 GMT
Server: Apache/2.4.39 (Win64) OpenSSL/1.1.1b mod_fcgid/2.3.9a mod_log_rotate/1.02
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
Cache-Control: max-age=0
Connection: keep-alive
Content-Length: 49
Content-Type: application/x-www-form-urlencoded
Host: www.xx.com
If-Modified-Since: Sat, 05 Feb 2022 16:23:15 GMT
If-None-Match: "ad4-5d747c8cc3c02"
Origin: http://www.xx.com
Referer: http://www.xx.com/25.html
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36
username: WWW
pass: 12531
submit: 登陆
这篇文章对您有用吗?

我们要如何帮助您?