Query-string encoding of a Javascript Object

前端 未结 30 3479
渐次进展
渐次进展 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 01:03

    This is a solution that will work for .NET backends out of the box. I have taken the primary answer of this thread and updated it to fit our .NET needs.

    function objectToQuerystring(params) {
    var result = '';
    
        function convertJsonToQueryString(data, progress, name) {
            name = name || '';
            progress = progress || '';
            if (typeof data === 'object') {
                Object.keys(data).forEach(function (key) {
                    var value = data[key];
                    if (name == '') {
                        convertJsonToQueryString(value, progress, key);
                    } else {
                        if (isNaN(parseInt(key))) {
                            convertJsonToQueryString(value, progress, name + '.' + key);
                        } else {
                            convertJsonToQueryString(value, progress, name + '[' + key+ ']');
                        }
                    }
                })
            } else {
                result = result ? result.concat('&') : result.concat('?');
                result = result.concat(`${name}=${data}`);
            }
        }
    
        convertJsonToQueryString(params);
        return result;
    }
    

提交回复
热议问题