18

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?

4

4 回答 4

20

您还可以使用traditionalajax 调用中的设置 http://api.jquery.com/jquery.ajax/#jQuery-ajax-settings

传统类型:布尔型

如果您希望使用传统的参数序列化风格,请将其设置为 true。

例如:

$.ajax({
 /*usual stuff */
 traditional: true
})
于 2014-01-08T15:58:10.810 回答
12

在 jQuery 1.4 中引入了键中带有括号的这种表示法来处理多维数组,或包含对象(或其他数组)本身的数组。这有助于反序列化器区分数组和原始值。例如,如果键中没有括号,则这两个变量将以相同的方式序列化:

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

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

使用括号符号,它们被编码为

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

k1=v2&k2=v2&k3=v3

分别。

于 2011-05-15T21:19:38.360 回答
3

可以将具有相同键名的多条数据发送到脚本。您可以通过[]在键名的末尾添加方括号来指定数据应被解释为数组来执行此操作。

执行此操作的功能是jQuery.param. 作为其工作原理的示例:

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

data是一个数组。当它被序列化时,它被呈现为data%5B%5D=value3&data%5B%5D=value4. 服务器端脚本会将其转换为数组。

于 2011-05-15T21:22:48.770 回答
2

这主要是一种命名约定——我认为来自 PHP——表明键 ( key3) 是多值的。由服务器对这些进行有意义的解码。

更多细节:http ://api.jquery.com/jQuery.param/

于 2011-05-15T21:19:16.273 回答