Convert JS Object to form data

前端 未结 18 1902
孤街浪徒
孤街浪徒 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 17:51

    If you have an object, you can easily create a FormData object and append the names and values from that object to formData.

    You haven't posted any code, so it's a general example;

    var form_data = new FormData();
    
    for ( var key in item ) {
        form_data.append(key, item[key]);
    }
    
    $.ajax({
        url         : 'http://example.com/upload.php',
        data        : form_data,
        processData : false,
        contentType : false,
        type: 'POST'
    }).done(function(data){
        // do stuff
    });
    

    There are more examples in the documentation on MDN

提交回复
热议问题