Sending nested FormData on AJAX

前端 未结 3 1815
走了就别回头了
走了就别回头了 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:48

    URL Encoded form data doesn't have any native way to express complex data structures. It only supports simple key=value pairs.

    ?foo=1&bar=2
    

    Most form data parsing libraries allow arrays of data using keys with the same name

    ?foo=1&foo=2
    

    PHP bolted its own syntax on top of that format:

    ?foo[]=1&foo[]=2
    

    which allowed for named keys in an associative array:

    ?foo[bar]=1&foo[baz]=2
    

    and nested arrays:

    ?foo[bar][level2a]=1&foo[bar][level2b]=2
    

    Due to the prevalence of PHP, jQuery adopted that syntax for generating form data when you pass a JavaScript object to data.

    If you want to use FormData then jQuery won't reprocess it for you.

    The effect you are seeing is because you are trying to put an object (I'm guessing a FormData instance, but you haven't showed that part of your code) as the second argument to append - where a string is expected.

    You need to generate the key names using PHP's syntax yourself.

    form_data_instance.append("Lvl_1-3[Lvl_1-3-1]", "something");
    form_data_instance.append("Lvl_1-3[Lvl_1-3-2]", "something");
    form_data_instance.append("Lvl_1-3[Lvl_1-3-3]", "something");
    

提交回复
热议问题