天天看点

JS动态模拟Form表单提交数据

分享知识  传递快乐

JS动态模拟Form表单提交数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button onclick="subForm()">提交</button>
</body>
<script type="text/javascript">

    var createInput = function (name, value) {
        var inputElement = document.createElement("input");
        inputElement.type = "hidden";
        inputElement.name = name;
        if (value != null) {
            inputElement.value = value;
        }
        return inputElement;
    }

    postForm = function (url) {
        // 创建表单
        var formElement = document.createElement("form");
        formElement.action = url;
        formElement.method = "post";
        // 打开新标签
        formElement.target = '_blank';
        formElement.style.display = "none";

        formElement.appendChild(createInput("name", "张三"));
        formElement.appendChild(createInput("age", 12));
        formElement.appendChild(createInput("sex", "男"));

        document.body.appendChild(formElement);
        formElement.submit();
        return formElement;
    }


    function subForm() {
        debugger;

        postForm("https://www.runoob.com");

        debugger;
    }

</script>
</html>      

继续阅读