Sending nested FormData on AJAX

前端 未结 3 1835
走了就别回头了
走了就别回头了 2020-12-31 04:09

I need to send some data using ajax and FormData, because I want to send a file and some other parameters. The way I usually send data is this:

$.ajax({
             


        
3条回答
  •  无人及你
    2020-12-31 04:36

    On my end, I stringify my nested parameters and parse them on the other end.

    For instance, if I want to pass:

    {"sthing":
      {"sthing":"sthing"},
      {"picture":
        {"legend":"great legend"},
        {"file":"great_picture.jpg"}
      }
    }
    

    Then I do:

    // On the client side
    const nestedParams = {"sthing":
                           {"sthing":"sthing"},
                           {"picture":
                             {"legend":"great legend"}
                           }
                         };
    const pictureFile = document.querySelector('input[type="file"]')[0];
    const formDataInstance = new FormData;
    formDataInstance.append("nested_params": JSON.stringify(nested_params);
    formDataInstance.append("file": document.querySelector('input[type="file"]')[0]);
    
    
    // On the server side
    params["nested_params"] = JSON.parse(params["nested_params"]);
    params["nested_params"]["sthing"]["picture"]["file"] = params["file"];
    

提交回复
热议问题