J'ai réalisé une implémentation qui prend en charge les objets et les tableaux imbriqués, c'est-à-dire :
var data = {
users: [
{
"name": "jeff",
"tasks": [
"Faire une chose",
"Faire une deuxième chose"
]
},
{
"name": "rick",
"tasks": [
"Never gonna give you up",
"Never gonna let you down"
]
}
]
}
Sera :
users[0][name]=jeff&users[0][tasks][0]=Faire%20une%20chose&users[0][tasks][1]=Faire%20une%20deuxième%20chose&users[1][name]=rick&users[1][tasks][0]=Never%20gonna%20give%20you%20up&users[1][tasks][1]=Never%20gonna%20let%20you%20down
Voici donc l'implémentation :
var isObj = function(a) {
if ((!!a) && (a.constructor === Object)) {
return true;
}
return false;
};
var _st = function(z, g) {
return "" + (g != "" ? "[" : "") + z + (g != "" ? "]" : "");
};
var fromObject = function(params, skipobjects, prefix) {
if (skipobjects === void 0) {
skipobjects = false;
}
if (prefix === void 0) {
prefix = "";
}
var result = "";
if (typeof(params) != "object") {
return prefix + "=" + encodeURIComponent(params) + "&";
}
for (var param in params) {
var c = "" + prefix + _st(param, prefix);
if (isObj(params[param]) && !skipobjects) {
result += fromObject(params[param], false, "" + c);
} else if (Array.isArray(params[param]) && !skipobjects) {
params[param].forEach(function(item, ind) {
result += fromObject(item, false, c + "[" + ind + "]");
});
} else {
result += c + "=" + encodeURIComponent(params[param]) + "&";
}
}
return result;
};
var data = {
users: [{
"name": "jeff",
"tasks": [
"Faire une chose",
"Faire une deuxième chose"
]
},
{
"name": "rick",
"tasks": [
"Never gonna give you up",
"Never gonna let you down"
]
}
]
}
document.write(fromObject(data));