form serialize javascript (no framework)

后端 未结 23 1642
一生所求
一生所求 2020-11-22 16:07

Wondering is there a function in javascript without jquery or any framework that allows me to serialize the form and access the serialized version?

23条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 16:43

    I've grabbed the entries() method of formData from @moison answer and from MDN it's said that :

    The FormData.entries() method returns an iterator allowing to go through all key/value pairs contained in this object. The key of each pair is a USVString object; the value either a USVString, or a Blob.

    but the only issue is that mobile browser (android and safari are not supported ) and IE and Safari desktop too

    but basically here is my approach :

    let theForm =  document.getElementById("contact"); 
    
    theForm.onsubmit = function(event) {
        event.preventDefault();
    
        let rawData = new FormData(theForm);
        let data = {};
    
       for(let pair of rawData.entries()) {
         data[pair[0]] = pair[1]; 
        }
        let contactData = JSON.stringify(data);
        console.warn(contactData);
        //here you can send a post request with content-type :'application.json'
    
    };
    

    the code can be found here

提交回复
热议问题