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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:05:57  来源:igfitidea点击:

passing an array to json.stringify

javascriptjqueryjson

提问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 datato 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

arrshould be declared as an object inside ArrayPushmethod because you are not using it like an array. Also inside the function you can just use this.idand this.valueyou don't have to create the jQueryobject. Try this

arr应该在ArrayPush方法内部声明为对象,因为您没有像数组一样使用它。同样在函数内部,您可以直接使用,this.idthis.value不必创建jQuery对象。试试这个

function ArrayPush($group) {
    var arr = {};
    $group.find('input[type=text],textarea').each(function () {
        arr[this.id] = this.value;
    });
    return arr;
}