使用原生js提交form表单

发布时间 2023-09-24 13:06:07作者: 刘东才

主要函数

    function form(formId,callback){
        try{
            const target=document.getElementById(formId);
            target.addEventListener("submit",(e)=>{
                e.preventDefault();
                const formData=new FormData(e.target);
                const formJson = Object.fromEntries(formData.entries());
                callback(formJson);
            })
        }catch(e){
            throw e;
        }
    }

 

 

测试函数

    form("myform",(res)=>{
        fetch("/url/test",{
            method:"post",
            headers:{
                "Context-Type":"application/json"
            },
            body:JSON.stringify(res)
        }).then((res)=>{
            console.log("data:",res)
        })
    })