Convert JS Object to form data

前端 未结 18 1888
孤街浪徒
孤街浪徒 2020-11-29 17:22

How can I can convert my JS Object to FormData?

The reason why I want to do this is, I have an object that I constructed out of the ~100 form field valu

18条回答
  •  野性不改
    2020-11-29 17:29

    Maybe you're looking for this, a code that receive your javascript object, create a FormData object from it and then POST it to your server using new Fetch API:

        let myJsObj = {'someIndex': 'a value'};
    
        let datos = new FormData();
        for (let i in myJsObj){
            datos.append( i, myJsObj[i] );
        }
    
        fetch('your.php', {
            method: 'POST',
            body: datos
        }).then(response => response.json())
            .then(objson => {
                console.log('Success:', objson);
            })
            .catch((error) => {
                console.error('Error:', error);
            });
    

提交回复
热议问题