[英]Why can't I append to my JSON object? (jQuery/Javascript)
I'm using the following code in an attempt to add a new attribute to bar object: 我正在使用以下代码来尝试向bar对象添加新属性:
$(document).ready(function(){
$('form').on("submit",preventDefault);
});
function preventDefault(e) {
e.preventDefault();
$url="contact/send";
bar = $('form').serialize();
bar["foo"]='xyz';
//bar.foo="123";
console.log(bar);
}
However I don't ever seem to get the value of bar.foo. 但是我似乎从未获得过bar.foo的价值。 If I look at the console in Chrome I always get a result similar to this:
如果我查看Chrome中的控制台,总是会得到类似以下的结果:
name=Grahame&email=foo%40bar.com&message=Hello.
Why am I not getting the value/property of foo? 为什么我没有得到foo的值/属性?
Other answers here talk about how one might get around this, but no one is explaining why this is happening, so I figured I'll give it a shot. 这里的其他答案是关于如何解决这个问题的,但没人能解释为什么会这样,所以我想我会试一试。
You call .serialize
which produces a string 您调用
.serialize
产生一个字符串
Strings in JavaScript are primitive value types, so when you add a property to it, it "autoboxes" becomes a String
reference type object for that call. JavaScript中的字符串是原始值类型,因此在向其添加属性时,“自动框”将成为该调用的
String
引用类型对象 。
You assign the property to it, which is added to the boxed object 您为其分配属性,该属性将添加到装箱的对象中
console.log(bar);
logs the bar object, which is already again a string which is a primitive value type. 记录bar对象,该对象已经是一个原始值类型的字符串。 Both because toString of the String type, and because of the
bar
being a primitive value type, you get the same initial value. 既由于String类型的toString,又由于
bar
是原始值类型,您将获得相同的初始值。
You can read more about this in the secret life of primitives in JavaScript. 您可以在JavaScript原语的秘密生活中了解有关此内容的更多信息。 Or in the specification
或在规格中
See How to add a value to jQuery serialize . 请参阅如何向jQuery序列化添加值 。 That has already been answered there.
那里已经回答了。
You can just use this: 您可以使用以下命令:
bar = $('form').serialize();
bar += '&foo=xyz';
console.log(bar);
Currently you're trying to use bar
as an array (or an object in your commented code). 当前,您正在尝试使用
bar
作为数组(或注释代码中的对象)。 .serialize()
actually generates a URL-ecoded string so you can simply append your value to it. .serialize()
实际上会生成一个URL编码的字符串,因此您只需将其值附加到该字符串即可。
bar
is serialized form data. bar
是序列化的表单数据。 It is a string not an object. 它是字符串而不是对象。
If you want to add data do it you need to serialize that data: 如果要添加数据,则需要序列化该数据:
bar += "&" + encodeURIComponent('foo') + "=" + encodeURIComponent('xyz');
(You can skip the encode URI components if you know that the data has no URL special characters in it). (如果您知道数据中没有URL特殊字符,则可以跳过编码URI组件)。
change to: 改成:
bar = $('form').serializeArray();
bar["foo"]='xyz';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.