HTML Form Submission Summary

HTML Form Submission Summary

Overview: With the rise of HTML5, the front end is becoming more and more diverse. For example, there are many ways to submit forms. The following summarizes the common form submission methods.

1. The most basic form submission.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>表单提交示例 - 基本表单提交</title>
</head>
<body>
<form action="/server_url" method="post" onsubmit="return beforeSubmit()">
    ID:<input id="username" type="text" name="username" />
    Password:<input id="password" type="password" name="password" />
    <input type="submit" value="Submit" />
</form>
<script type="text/javascript">
    function beforeSubmit() {
    
    
        var username = document.getElementById('username').value;
        var password = document.getElementById('password').value;
        if (username.length < 6 || password.length < 6) {
    
    
            alert('格式不正确!');
            return false;
        } else {
    
    
            return true;
        }
    }
</script>
</body>
</html>

The above code is very simple. Note that the onsubmit attribute in the from form must have a return, otherwise it will have no effect. The onsubmit attribute is optional. If you need js to do some simple validation on the form, you can use this method. If js fails the validation, it will return false, and the form will not be submitted.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>表单提交示例 - 基本表单提交2</title>
</head>
<body>
<form id="form_login" action="/server_url" method="post">
    ID:<input id="username" type="text" name="username" />
    Password:<input id="password" type="password" name="password" />
</form>
<button id="btn-submit" onclick="beforeSubmit()">Submit</button>
<script type="text/javascript">
    var loginForm = document.getElementById('form_login');
    function beforeSubmit() {
    
    
        var username = document.getElementById('username').value;
        var password = document.getElementById('password').value;
        if (username.length < 6 || password.length < 6) {
    
    
            alert('格式不正确!');
        } else {
    
    
            loginForm.submit();
        }
    }
</script>
</body>
</html>

A little bit of modification has been made above. The form element has added an id, removed onsubmit, and an input button of type submit has also been removed. Instead, a normal button is added outside from.

Clicking this button will trigger a piece of js. In this js, data verification can be done. If the verification is passed, the form will be submitted through js. The function of adding id to the form form is to make it easier for js to obtain form elements.

The above two methods are the most basic ways to submit the form, and you can choose at will in actual work.

2.FormData form submission.

Next, let's look at submitting the form through HTML5's FormData. The submission method of this form is asynchronous, and the address of the browser will not change.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>表单提交示例 - FormData</title>
</head>
<body>
<form name="login_form" action="/server_url" method="post">
    ID:<input id="username" type="text" name="username" />
    Password:<input id="password" type="password" name="password" />
</form>
<button id="btn-submit" onclick="beforeSubmit()">Submit</button>
<script type="text/javascript">
    function beforeSubmit() {
    
    
        var username = document.getElementById('username').value;
        var password = document.getElementById('password').value;
        if (username.length < 6 || password.length < 6) {
    
    
            alert('格式不正确!');
            return;
        }
        
        // 1.创建一个FormData对象,直接把我们的表单传进去  
        var formData = new FormData(document.forms.namedItem("login_form"));
        
        // 2.创建一个http请求对象
        var xmlHttpRequest = new XMLHttpRequest();
        
        xmlHttpRequest.open('post', '/server_url');
        xmlHttpRequest.onload = function(resp) {
    
    
            if (xmlHttpRequest.status == 200) {
    
    
                alert('提交成功!');
            } else {
    
    
                alert('Error:' + xmlHttpRequest.status);
            }
        };
        xmlHttpRequest.send(formData);
    }
</script>
</body>
</html>

Compared with the previous two submission methods, asynchronous submission is the biggest difference. One of the benefits brought about by this method is that it is very cool to upload files asynchronously. Add an input element of type file to the form, and the file can be uploaded directly, which is very convenient.

3. Use jquery to send the FormData form.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>表单提交示例 - JQuery发送FormData</title>
</head>
<body>
<form name="login_form" action="/server_url" method="post">
    ID:<input id="username" type="text" name="username" />
    Password:<input id="password" type="password" name="password" />
</form>
<button id="btn-submit" onclick="beforeSubmit()">Submit</button>

<script type="text/javascript" src="/res/lib/jquery-1.11.3.js"></script>
<script type="text/javascript">
    function beforeSubmit() {
    
    
        var username = document.getElementById('username').value;
        var password = document.getElementById('password').value;
        if (username.length < 6 || password.length < 6) {
    
    
            alert('格式不正确!');
            return;
        }
        
        // 1.创建一个FormData对象,直接把我们的表单传进去  
        var formData = new FormData(document.forms.namedItem("login_form"));
        
        // 2.通过jquery发送出去
        $.ajax({
    
    
            url: "/server_url.php",
            type: "POST",
            data: formData,
            processData: false,  // 告诉jQuery不要去处理发送的数据
            contentType: false   // 告诉jQuery不要去设置Content-Type请求头
        }).done(function(resp) {
    
    
            alert('success!');
        }).fail(function(err) {
    
    
            alert('fail!')
        });
        
    }
</script>
</body>
</html>

4. Send binary file data directly.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>http请求发送二进制文件</title>
</head>
<body>
<input id="avatar" type="file" name="avatar" />
<button id="btn-submit" onclick="beforeSubmit()">Submit</button>
<script type="text/javascript" src="/res/lib/jquery-1.11.3.js"></script>
<script type="text/javascript">
    function beforeSubmit() {
    
    
        var avatar = document.getElementById('avatar').files[0];
        if (typeof avatar === 'undefined') {
    
    
            alert('请选择一个图片!');
            return;
        }
        var reader = new FileReader();
        // reader.readAsDataURL(avatar); // 读取的是图片的base64字符串,可以直接设置给图片的src属性
        // reader.readAsBinaryString(avatar); // 读取的是图片的二进制数据
        // reader.readAsText(avatar); // 以字符串读取文件内容,一般用于读取字符文件
        reader.readAsArrayBuffer(avatar);
        reader.onload = function() {
    
    
            var data = this.result;

            // 原生http请求发送二进制文件
            var xmlHttpRequest = new XMLHttpRequest();
            xmlHttpRequest.open('post', '/server_url.php');
            xmlHttpRequest.onload = function() {
    
    
                if (xmlHttpRequest.status == 200) {
    
    
                    alert('success!');
                } else {
    
    
                    alert('Error:' + xmlHttpRequest.status);
                }
            };
            xmlHttpRequest.send(data);

            // 用jquery发送二进制文件
            $.ajax({
    
    
                url: "/server_url.php",
                type: "POST",
                data: data,
                processData: false,  // 告诉jQuery不要去处理发送的数据
                contentType: false   // 告诉jQuery不要去设置Content-Type请求头
            }).done(function(resp) {
    
    
                alert('success!');
            }).fail(function(err) {
    
    
                alert('fail!')
            });
        };        
    }
</script>
</body>
</html>

The server receives:

<?php
$fp = fopen('avatar.png', 'wb');
$size = fwrite($fp, file_get_contents('php://input'));
print 'success';

Receive binary data as a stream. Finish! ! !

Guess you like

Origin blog.csdn.net/sunny_day_day/article/details/128132417