0

我有一个对象说图像

        look : {
            name : "hello baby",
            tag_list : "hello",
            collection_id : 1,
            category_id : 1
        },

我想序列化这个对象,以便它可以通过POST / GET请求发送到服务器。我不能为此目的使用 JQUery。

看[名字]=你好

4

6 回答 6

3

尝试这个:

var a = [];
for (var p in obj)
    a.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
var qstring = a.join("&");
于 2012-08-03T10:10:17.117 回答
0

Try using for..in loop. It gets each variable from object.

function serialize(obj)
{
     var serialized = "";
     for (variable in obj)
     {
        if(serialized != "") serialized += "&";
        serialized += variable + "=" + encodeURIComponent(obj[variable]);
     }
}
于 2012-08-03T10:07:40.120 回答
0

Code taken from http://www.codeproject.com/Tips/46827/Serialize-Object-in-Javascript

function serialize(obj)
    {
        var returnVal;
        if(obj != undefined){
        switch(obj.constructor)
        {
            case Array:
                var vArr="[";
                for(var i=0;i<obj.length;i++)
                {
                    if(i>0) vArr += ",";
                    vArr += serialize(obj[i]);
                }
                vArr += "]"
                return vArr;
            case String:
                returnVal = escape("'" + obj + "'");
                return returnVal;
            case Number:
                returnVal = isFinite(obj) ? obj.toString() : null;
                return returnVal;               
            case Date:
                returnVal = "#" + obj + "#";
                return returnVal;       
            default:
                if(typeof obj == "object"){
                    var vobj=[];
                    for(attr in obj)
                    {
                        if(typeof obj[attr] != "function")
                        {
                            vobj.push('"' + attr + '":' + serialize(obj[attr]));
                        }
                    }
                        if(vobj.length >0)
                            return "{" + vobj.join(",") + "}";
                        else
                            return "{}";
                }       
                else
                {
                    return obj.toString();
                }
        }
        }
        return null;
    }
于 2012-08-03T10:08:53.613 回答
0

For plain one dimensional objects, you can use

var ser ="";
for (var o in look) ser += "&"+o+"="+encodeURIComponent(look[o]);
alert(ser.substring(1));
于 2012-08-03T10:09:34.673 回答
0

会为您的对象添加一个 stringify 方法,并为您的字符串添加一个 parseJSON 方法。

来源:JSON.org

于 2012-08-03T10:12:58.733 回答
0

只需使用:

var look = {
            name : "hello baby",
            tag_list : "hello",
            collection_id : 1,
            category_id : 1
        };

   var serialized_object = JSON.stringify(look);  // to serialize an object
   var deserialized_object = eval('('+ serialized_object + ')');  // to deserialize an object
于 2012-08-03T10:13:58.457 回答