Query-string encoding of a Javascript Object

前端 未结 30 2995
渐次进展
渐次进展 2020-11-22 00:23

Do you know a fast and simple way to encode a Javascript Object into a string that I can pass via a GET Request?

No jQuery, no

30条回答
  •  时光取名叫无心
    2020-11-22 00:56

    Refer from the answer @user187291, add "isArray" as parameter to make the json nested array to be converted.

    data : {
                        staffId : "00000001",
                        Detail : [ {
                            "identityId" : "123456"
                        }, {
                            "identityId" : "654321"
                        } ],
    
                    }
    

    To make the result :

    staffId=00000001&Detail[0].identityId=123456&Detail[1].identityId=654321

    serialize = function(obj, prefix, isArray) {
            var str = [],p = 0;
            for (p in obj) {
                if (obj.hasOwnProperty(p)) {
                    var k, v;
                    if (isArray)
                        k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
                    else
                        k = prefix ? prefix + "." + p + "" : p, v = obj[p];
    
                    if (v !== null && typeof v === "object") {
                        if (Array.isArray(v)) {
                            serialize(v, k, true);
                        } else {
                            serialize(v, k, false);
                        }
                    } else {
                        var query = k + "=" + v;
                        str.push(query);
                    }
                }
            }
            return str.join("&");
        };
    
        serialize(data, "prefix", false);
    

提交回复
热议问题