Query-string encoding of a Javascript Object

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

    Just another way (no recursive object):

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

提交回复
热议问题