document.write outputing "&" as & in URL

They have: 426 posts

Joined: Feb 2005

So i am having more trouble with Javascript!

Everything was working great until i made a slight change to my script - just added a new function and assigned the value to a variable that was before static.

i am using document.write to print out a tag with a dynamic url inside for the source.

The only problem is for some reason it is printing the & in the URL as & and becuase of this my include will not work (its a JSON external URL and im using the callback function).

For example it do:

document.write('<scr' + 'ipt src="http://jsonsource.com/index.php?j=t&y=r&h=4" type="text/javascript"><\/scr' + 'ipt>');

but it is printing the "&" as &amp;

It is stopping the JSON from working?

I even took the actual value of the URL and inserted it as innerHTML to another element on the page and it was using the &.

Can anyone advise me how i can get javascript to print it as & and not &amp;

would be really greatful of any help.

greg's picture

He has: 1,581 posts

Joined: Nov 2005

Have you tried using the entity? &amp;

document.write('<scr' + 'ipt src="http://jsonsource.com/index.php?j=t&amp;y=r&amp;h=4" type="text/javascript"><\/scr' + 'ipt>');

It's common practice anyway...

W3C wrote:
If ampersands are not encoded, the characters after them up to the next semi-colon can be interpreted as the name of a entity by the user agent. The document could also be considered not "well-formed" by an XML processor

decibel.places's picture

He has: 1,494 posts

Joined: Jun 2008

They have: 426 posts

Joined: Feb 2005

Yes i have tried all of these options, escaping and using &amp; and none appear to work. Only when i use the & does it work.

i did previously createElement and appendChild to insert the tag on the page. However, the callback function did not work. Only when i document.write did it work.

Any ideas on this?

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.