开发者

Is this JavaScript encoding properly written?

I have tried some tips I was given on regards URL encoding but I have no success so far. First, I was given this format,

var url = "http://www.polyvore.com/cgi/add?title=" 
      + encodeURIComponent(%%GLOBAL_ProductNa开发者_如何学运维me%%) 
      + "&url=" + encodeURIComponent("http://lilaboutique.co.uk/products/" 
          + encodeURIComponent(%%GLOBAL_ProductName%%) 
          + "&imgurl=" + encodeURIComponent(%%GLOBAL_ThumbImageURL%%) 
          + "&desc=" + encodeURIComponent(%%GLOBAL_ProductDesc%%) 
          + "&price=" + encodeURIComponent(%%GLOBAL_ProductPrice%%));

which never got to be passed to the href dunno for what reason. Then I played with it some more,

var url = "http://www.polyvore.com/cgi/add?title=encodeURIComponent(%%GLOBAL_ProductName%%)&url=http://lilaboutique.co.uk/products/encodeURIComponent(%%GLOBAL_ProductName%%)&imgurl=encodeURIComponent(%%GLOBAL_ThumbImageURL%%)&desc=encodeURIComponent(%%GLOBAL_ProductDesc%%)&price=encodeURIComponent(%%GLOBAL_ProductPrice%%)";

this time the URL was passed but the values were mixed between the appropriate and other fields displaying the encoding function itself.

Any help clarifying my mistakes is greatly appreciated. I would like to encode just price and description, seems to be the fields giving problems.

A regular link does render without problems

var url = "www.google.com";

var myAnchor = document.getElementById('myAnchor');

myAnchor.href = url;

Thanks for any help


Nicer, cleaner way of doing this:

var toEncode = {
  title:    '%%GLOBAL_ProductName%%',
  url:      'http://lilaboutique.co.uk/products/%%GLOBAL_ProductName%%',
  imgurl:   '%%GLOBAL_ThumbImageURL%%',
  desc:     '%%GLOBAL_ProductDesc%%',
  price:    '%%GLOBAL_ProductPrice%%'
};

var index, queryString = '';

for (index in toEncode)
{
  queryString += index + '=' + encodeURIComponent(toEncode[index]) + '&';
}

var url = "http://www.polyvore.com/cgi/add?" + queryString;


jQuery's $.param(obj) is very nice.

In general though I would take a similar approach if you wanted to roll your own. Make a function that accepts an Object, and returns a query string. Then in your server template, you have:

var urlData = {
  url: "http://lilaboutique.co.uk/products/",
  imgurl: "%%GLOBAL_ThumbImageURL%%",
  desc: "%%GLOBAL_ProductDesc%%"
  // etc...
}

var url = "http://www.polyvore.com/cgi/add?" + $.param(urlData);

Or whatever conversion function you want to use.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜