views:

285

answers:

4

Hi!

I have this bit of code:

...
var aData = request.responseXML.getElementsByTagName('data')[0];
var sDescription = aData.getElementsByTagName('description')[0].firstChild.data;

alert(escape(sDescription));
document.getElementById('tempLabourLineDescription').value = sDescription;
...

sDescription is outputting: SUPPORT ASSY-FUEL TANK MOUNTING, R&R (LH) (L-ENG)

I think it is obvious what i want to do here (get the sDescription in to a field called tempLabourLineDescription but that just will not work.

However, if i in my php script replace or delete the &-char from that string it all works fine. So i thought, just escape the darn string. But that will just not work. alerting the string doesn't work either until i remove the &-character.

What is doing this? Is sDescription not a string when it comes out of the xml file? How can i solve this?

+2  A: 

The answer is in this snippet:

var aData = request.responseXML...

You're expecting XML. An & by itself is not legal XML. You need to output your result like this:

SUPPORT ASSY-FUEL TANK MOUNTING, R&R (LH) (L-ENG)

Joel Coehoorn
A: 

You escape the ampersand by using the HTML eqv. &

George
+1  A: 

It's very difficult to tell without seeing your output script, but the first thing to try is to mask the ampersand: &

The neater way, though, would be to add CDATA to your XML output:

<data><![CDATA[SUPPORT ASSY-FUEL TANK MOUNTING, R&R (LH) (L-ENG)]]></data>

your XML parser on client side should understand it no problem.

Pekka
half-a-nerd
Nice! It also makes it possible to use `<` and `>` without having to escape it.
Pekka
A: 

If you are unable to alter the XML output from the server (it's not your app or some other issue), a "hack" fix would be:

function htmlizeAmps(s){
  return s.replace(/\x26/g,"&amp;"); //globalreplace "&" (hex 26) with "&amp;"
}
document.getElementById('tempLabourLineDescription').value = htmlizeAmps(sDescription);
Graza