我有一个对象说图像
look : {
name : "hello baby",
tag_list : "hello",
collection_id : 1,
category_id : 1
},
我想序列化这个对象,以便它可以通过POST / GET请求发送到服务器。我不能为此目的使用 JQUery。
看[名字]=你好
我有一个对象说图像
look : {
name : "hello baby",
tag_list : "hello",
collection_id : 1,
category_id : 1
},
我想序列化这个对象,以便它可以通过POST / GET请求发送到服务器。我不能为此目的使用 JQUery。
看[名字]=你好
尝试这个:
var a = [];
for (var p in obj)
a.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
var qstring = a.join("&");
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]);
}
}
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;
}
For plain one dimensional objects, you can use
var ser ="";
for (var o in look) ser += "&"+o+"="+encodeURIComponent(look[o]);
alert(ser.substring(1));
只需使用:
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