1

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

6
  • 4
    Incidentally, <img /> is a void element, it has no closing tag. And if you're appending to an existing URL, you want encodeURIComponent(), not encodeURI(). Commented Oct 29, 2014 at 12:11
  • 1
    No you should do decodeURI right? Commented Oct 29, 2014 at 12:12
  • i am thinking that mi8 not be problem,,if it is the actual problem all image names with space and with out space should't hv rendred..plz correct me if im wrong Commented Oct 29, 2014 at 12:13
  • Can you give us sample output of console.log( data.d[i] ). Commented Oct 29, 2014 at 12:15
  • encrodeURIComponent is wrking ..Thx for ur suggestions @David Commented Oct 29, 2014 at 12:16

1 Answer 1

2

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] ) + "\" ....
Sign up to request clarification or add additional context in comments.

2 Comments

simply encodeURIComponent is worked for me...but what ever u suggested are alsoo worthyy
Great! Please accept this answer iff it was helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.