简体   繁体   中英

Url encoding in javascript

I am binding a div with the image list which returned from server side method.

Like below:

  $("#GalleryPhotos").append("<div class='thumbnail'><a rel='group1' data-caption='caption'  class='fancybox'  href=" + data.d[i] + "><img  height='120' width='150' src=" + data.d[i] + "></img></a> </div> ");

I will get complete url

 < img src= "/UploadedFiles/Gallery/CricketAlbum/5335.jpg" />

It is showing correctly if there is no space in file name, But in case if there is a space in file name it is rendering as:

 < img  src="/UploadedFiles/Gallery/Birdst" album="" sample_05.jpg="" />

I tried javascript built in function encode like this src="+ encodeURI(data.d[i])+" But still my img getting rendered as in second case..Please help me somebody

As suggested by @DavidThomas, use encodeURIComponent() :

 ..  width='150' src='" + encodeURIComponent( data.d[i] ) + "'></a> ..

Special Note

The primary reason this was not working is because you were not putting the value of src in quotes. In effect you were writing:

<img  src=/UploadedFiles/Gallery/Birdst album sample_05.jpg />

Which would process into the weird attributes you were seeing. However, if you had quoted the value, the URL may as well have worked:

< img  src='/UploadedFiles/Gallery/Birdst album sample_05.jpg' />

The code should have been:

.... src='" + data.d[i] + "'>....

Or:

.... src=\"" + data.d[i] + "\">....

Now that you know that much, however, it is always safer to escape URLs as unescaped characters may produce undesired results in certain system:

.... src=\"" + encodeURIComponent( data.d[i] ) + "\" ....

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