issue with brackets in jQuery Form Data when sending data as json

半腔热情 提交于 2019-11-27 12:59:23

问题


I have the object

    var dataformdata={"key1":"value1","key2":"value2"};

then I add some more values with the same key(key3) like this

    dataformdata.key3 = [];
    dataformdata.key3.push("value3");
    dataformdata.key3.push("value4");

I do the above in an each slope. It all works except when sending the dataformdata object via the jQuery ajax function in the browser console I see that there are brackets in the key ...

$.ajax({ type: "POST", url: "/", data: dataformdata,...

This is what I see in the browser console:

key1:value1
key2:value2
key3%5B%5D:value3
key3%5B%5D:value4

It should work because in the jQuery.ajax() docs it says

Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting

But why are the brackets (%5B%5D) in the key?


回答1:


This notation with the brackets in the key was introduced in jQuery 1.4 to deal with multi-dimensional arrays, or arrays containing objects (or other arrays) themselves. This helps the deserializer to differentiate between an array and a primitive value. For example, if you didn't have the brackets in the key, those two variables would be serialized the same way:

var v1 = { "k1":"v1", "k2":"v2", "k3":["v3"] };

and

var v1 = { "k1":"v1", "k2":"v2", "k3":"v3" };

With the bracket notation, they're encoded as

k1=v2&k2=v2&k3[]=v3

and

k1=v2&k2=v2&k3=v3

respectively.




回答2:


you can also use the traditional settings in the ajax call http://api.jquery.com/jquery.ajax/#jQuery-ajax-settings

traditional Type: Boolean

Set this to true if you wish to use the traditional style of param serialization.

for example:

$.ajax({
 /*usual stuff */
 traditional: true
})



回答3:


It is possible to send multiple pieces of data with the same key name to a script. You can do this by adding square brackets [] to the end of the key name to designate that the data should be interpreted as an array.

The function that does this is jQuery.param. As an example of how this works:

$.param({
    data: ['value3', 'value4']
});

data is an array. When it is serialized, it is rendered as data%5B%5D=value3&data%5B%5D=value4. The serverside script will convert this into an array.




回答4:


This is mostly a naming convention — I think from PHP — that indicates that the key (key3) is multivalued. It's up to the server to decode these meaningfully.

More details: http://api.jquery.com/jQuery.param/



来源:https://stackoverflow.com/questions/6011284/issue-with-brackets-in-jquery-form-data-when-sending-data-as-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!