是否有一个快速和简单的方法来编码JavaScript对象到字符串,我可以通过GET请求传递?

没有jQuery,没有其他框架-只有纯JavaScript:)


当前回答

看起来好一点

objectToQueryString(obj, prefix) {
    return Object.keys(obj).map(objKey => {
        if (obj.hasOwnProperty(objKey)) {
            const key = prefix ? `${prefix}[${objKey}]` : objKey;
            const value = obj[objKey];

            return typeof value === "object" ?
                this.objectToQueryString(value, key) :
                `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
        }

        return null;
    }).join("&");
}

其他回答

如果您需要发送任意对象,那么GET是一个坏主意,因为有限制的url长度,用户代理和web服务器将接受。我的建议是建立一个名称-值对数组来发送,然后建立一个查询字符串:

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() );

jQuery有一个函数jQuery.param()。如果你已经在使用它,你可以使用这个:

例子:

var params = { width:1680, height:1050 };
var str = jQuery.param( params );

STR现在包含宽度=1680&高度=1050。

const buildSortedQuery = (args) => { 返回种(args) .sort () .map(key => { 返回window.encodeURIComponent(关键) + ' = ' + window.encodeURIComponent (args(例子)); }) . join (' & '); }; console.log (buildSortedQuery ({ Foo:“你好”, 栏:“100%” })); / /酒吧= 100% 25 foo =你好% 20

对于TS

const convertQueryToString = (data: { [x: string]: any }): string => { const serialize = (obj: { [x: string]: any }, prefix?: string): string => { const str = []; let p; for (p in obj) { if (obj.hasOwnProperty(p)) { const k = prefix ? `${prefix}[${p}]` : p; const v = obj[p]; str.push( v !== null && typeof v === 'object' ? serialize(v, k) : `${encodeURIComponent(k)}=${encodeURIComponent(v)}` ); } } return str.join('&'); }; return serialize(data); };

另一种方法(没有递归对象):

   getQueryString = function(obj)
   {
      result = "";

      for(param in obj)
         result += ( encodeURIComponent(param) + '=' + encodeURIComponent(obj[param]) + '&' );

      if(result) //it's not empty string when at least one key/value pair was added. In such case we need to remove the last '&' char
         result = result.substr(0, result.length - 1); //If length is zero or negative, substr returns an empty string [ref. http://msdn.microsoft.com/en-us/library/0esxc5wy(v=VS.85).aspx]

      return result;
   }

alert( getQueryString({foo: "hi there", bar: 123, quux: 2 }) );