javascript – 如何将Object序列化为URL查询参数列表?

2019-10-08
在不知道 JavaScript对象的键的情况下,我该如何转换…

var obj = {
   param1: 'something',
   param2: 'somethingelse',
   param3: 'another'
}

obj[param4] = 'yetanother';

… INTO …

var str = 'param1=something&param2=somethingelse&param3=another&param4=yetanother';

…?

var str = "";
for (var key in obj) {
    if (str != "") {
        str += "&";
    }
    str += key + "=" + encodeURIComponent(obj[key]);
}

示例:http://jsfiddle.net/WFPen/