Query-string encoding of a Javascript Object

前端 未结 30 2916
渐次进展
渐次进展 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:44

    Do you need to send arbitrary objects? If so, GET is a bad idea since there are limits to the lengths of URLs that user agents and web servers will accepts. My suggestion would be to build up an array of name-value pairs to send and then build up a query string:

    function QueryStringBuilder() {
        var nameValues = [];
    
        this.add = function(name, value) {
            nameValues.push( {name: name, value: value} );
        };
    
        this.toQueryString = function() {
            var segments = [], nameValue;
            for (var i = 0, len = nameValues.length; i < len; i++) {
                nameValue = nameValues[i];
                segments[i] = encodeURIComponent(nameValue.name) + "=" + encodeURIComponent(nameValue.value);
            }
            return segments.join("&");
        };
    }
    
    var qsb = new QueryStringBuilder();
    qsb.add("veg", "cabbage");
    qsb.add("vegCount", "5");
    
    alert( qsb.toQueryString() );
    

提交回复
热议问题