Forum Moderators: open

Message Too Old, No Replies

Unescaped & (ampersand)

javascript code does'nt work if I escape the &

         

oluoch28394

1:22 am on Feb 7, 2009 (gmt 0)

10+ Year Member



I'm new to javascript and I got this script from "Javascript For Dummies":

<script type="text/javascript" language="javascript">
var xmlhttp = false;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}

if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
function makerequest(serverPage, objID) {
var obj = document.getElementById(objID);
xmlhttp.open("GET", serverPage);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
</script>

The makerequest() function works fine however the code does not validate because of the &&. If i escape them with &amp; then the function does not work but the page validates. Any help would be appreciated as I don't want to host an invalid page. The book is from 2006 but that can't be the reason, can it?

astupidname

1:38 am on Feb 7, 2009 (gmt 0)

10+ Year Member



I have to assume that you are using this javascript on an xhtml page. Because of some of the special characters used in javascript such as < > & etc.. javascript code on an xhtml page will not validate unless you wrap the code inside of CDATA tags. Example:
<script type="text/javascript">
/*<![CDATA[*/

//place javascript code in here

/*]]>*/
</script>

The CDATA opening and closing tags are only required inside of javascript tags which are actually on the page, and are not necessary if the script tags are just an src link to an external .js file (which also does not need the CDATA tags inside)

oluoch28394

12:52 am on Feb 8, 2009 (gmt 0)

10+ Year Member



Thanks, good to know, I'll give it a go. The book made no mention of this.