Convert JS Object to form data

前端 未结 18 1890
孤街浪徒
孤街浪徒 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:36

    I had a scenario where nested JSON had to be serialised in a linear fashion while form data is constructed, since this is how server expects values. So, I wrote a small recursive function which translates the JSON which is like this:

    {
       "orderPrice":"11",
       "cardNumber":"************1234",
       "id":"8796191359018",
       "accountHolderName":"Raj Pawan",
       "expiryMonth":"02",
       "expiryYear":"2019",
       "issueNumber":null,
       "billingAddress":{
          "city":"Wonderland",
          "code":"8796682911767",
          "firstname":"Raj Pawan",
          "lastname":"Gumdal",
          "line1":"Addr Line 1",
          "line2":null,
          "state":"US-AS",
          "region":{
             "isocode":"US-AS"
          },
          "zip":"76767-6776"
       }
    }
    

    Into something like this:

    {
       "orderPrice":"11",
       "cardNumber":"************1234",
       "id":"8796191359018",
       "accountHolderName":"Raj Pawan",
       "expiryMonth":"02",
       "expiryYear":"2019",
       "issueNumber":null,
       "billingAddress.city":"Wonderland",
       "billingAddress.code":"8796682911767",
       "billingAddress.firstname":"Raj Pawan",
       "billingAddress.lastname":"Gumdal",
       "billingAddress.line1":"Addr Line 1",
       "billingAddress.line2":null,
       "billingAddress.state":"US-AS",
       "billingAddress.region.isocode":"US-AS",
       "billingAddress.zip":"76767-6776"
    }
    

    The server would accept form data which is in this converted format.

    Here is the function:

    function jsonToFormData (inJSON, inTestJSON, inFormData, parentKey) {
        // http://stackoverflow.com/a/22783314/260665
        // Raj: Converts any nested JSON to formData.
        var form_data = inFormData || new FormData();
        var testJSON = inTestJSON || {};
        for ( var key in inJSON ) {
            // 1. If it is a recursion, then key has to be constructed like "parent.child" where parent JSON contains a child JSON
            // 2. Perform append data only if the value for key is not a JSON, recurse otherwise!
            var constructedKey = key;
            if (parentKey) {
                constructedKey = parentKey + "." + key;
            }
    
            var value = inJSON[key];
            if (value && value.constructor === {}.constructor) {
                // This is a JSON, we now need to recurse!
                jsonToFormData (value, testJSON, form_data, constructedKey);
            } else {
                form_data.append(constructedKey, inJSON[key]);
                testJSON[constructedKey] = inJSON[key];
            }
        }
        return form_data;
    }
    

    Invocation:

            var testJSON = {};
            var form_data = jsonToFormData (jsonForPost, testJSON);
    

    I am using testJSON just to see the converted results since I would not be able to extract the contents of form_data. AJAX post call:

            $.ajax({
                type: "POST",
                url: somePostURL,
                data: form_data,
                processData : false,
                contentType : false,
                success: function (data) {
                },
                error: function (e) {
                }
            });
    

提交回复
热议问题