简体   繁体   中英

Convert javascript object into a url query

I am trying to do the opposite of this question , namely, convert a JavaScript object into the query at the end of a url. This is for a potentially huge, and completely randomized string in terms of keys/values. For example,

activity = {myKey:"randomString"}

'<img src="images/image.gif?' + activity + '">'

Would give me back:

<img src='images/image.gif?{myKey:"randomString"}'>
var queryValues={
  param:"0",
  s:"stack",
  o:"overflow",
  myKey:"randomString"
};
var qparts=Object.keys(queryValues).map(function(k){
  return [k,queryValues[k]].map(encodeURIComponent).join("=");
});
var queryString=qparts.length?"?"+qparts.join("&"):"";


/*
queryString:
?param=0&s=stack&o=overflow&myKey=randomString
*/

Then modify the original url by concatenating with the queryString. Like so:

images/image.gif?param=0&s=stack&o=overflow&myKey=randomString

Also, from your question, you wanted a url that looks like this:

images/image.gif?{myKey:"randomString"}

Which appears malformed and not quite the opposite of what was posted in the other question you linked to. So I gave you a snippet to produce a well-formed query string instead.

var myURL = '<img src="images/image.gif?' + JSON.stringify(activity) + '">';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM