JSON格式发送数据时,jQuery Form Data中括号出现问题 [英] issue with brackets in jQuery Form Data when sending data as json

查看:599
本文介绍了JSON格式发送数据时,jQuery Form Data中括号出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象

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

然后我像这样用相同的键(key3)添加更多的值

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

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

我在每个坡度上都进行上述操作.除了通过浏览器控制台中的jQuery ajax函数发送dataformdata对象时,所有方法都有效,我看到键中有括号...

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, ...

$.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

它应该工作,因为在jQuery.ajax()文档中它说

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

对象必须是键/值对.如果value是一个Array,则jQuery根据传统设置的值使用相同的键序列化多个值

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

但是为什么键中的括号(%5B%5D)是这样?

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

推荐答案

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

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"] };

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

使用方括号表示法,它们被编码为

With the bracket notation, they're encoded as

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

k1=v2&k2=v2&k3=v3

分别.

这篇关于JSON格式发送数据时,jQuery Form Data中括号出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆