javascript 将数组传递给 json.stringify
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8943737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
passing an array to json.stringify
提问by bflemi3
I'm trying to pass an array to json.stringify but the returned value is coming back empty.
我正在尝试将数组传递给 json.stringify 但返回的值返回空。
JSON.stringify({ json: data }) // returns `{"json":[]}`
And here would be the contents of data:
这是数据的内容:
data[from] = "[email protected]"
data[to] = "[email protected]"
data[message] = "testmessage"
jquery:
查询:
function SubmitUserInformation($group) {
var data = {};
data = ArrayPush($group);
$.ajax({
type: "POST",
url: "http://www.mlaglobal.com/components/handlers/FormRequestHandler.aspx/EmailFormRequestHandler",
data: JSON.stringify({ json: data }),
dataType: 'json',
contentType: "application/json; charset=utf-8",
cache: false,
success: function (msg) {
if (msg) {
$('emailForm-content').hide();
$('emailForm-thankyou').show();
}
},
error: function (msg) {
form.data("validator").invalidate(msg);
}
});
}
function ArrayPush($group) {
var arr = new Array();
$group.find('input[type=text],textarea').each(function () {
arr[$(this).attr('id')] = $(this).val();
});
return arr;
}
采纳答案by Adam Rackis
data = ArrayPush($group);
Is re-assigning data
to be an array, so all your expando properties are not being stringified.
重新分配data
为数组,因此您的所有 expando 属性都不会被字符串化。
Inside your ArrayPush method, change
在 ArrayPush 方法中,更改
var arr = new Array();
to
到
var obj = { };
回答by ShankarSangoli
arr
should be declared as an object inside ArrayPush
method because you are not using it like an array. Also inside the function you can just use this.id
and this.value
you don't have to create the jQuery
object. Try this
arr
应该在ArrayPush
方法内部声明为对象,因为您没有像数组一样使用它。同样在函数内部,您可以直接使用,this.id
而this.value
不必创建jQuery
对象。试试这个
function ArrayPush($group) {
var arr = {};
$group.find('input[type=text],textarea').each(function () {
arr[this.id] = this.value;
});
return arr;
}