How to read (get contents) of CDATA section in XML with Javascript ?

P

Pugi!

Using AJAX I want to send some information from the server (php-page)
as XML to the client. The contents can be very divers so I have to use
XML instead of text. On one occasion the contents is html, I can put
this in a CDATA section with PHP, but how do I retrieve that
information with Javascript and put the HTML in a div ?

thanx,

Pugi!
 
M

Martin Honnen

Pugi! said:
Using AJAX I want to send some information from the server (php-page)
as XML to the client. The contents can be very divers so I have to use
XML instead of text. On one occasion the contents is html, I can put
this in a CDATA section with PHP, but how do I retrieve that
information with Javascript and put the HTML in a div ?

A CDATA section shows up as a CDATA section node (nodeType is 4) in the
DOM where the contents of the CDATA section can be accessed as e.g.
node.nodeValue
or
node.data
A CDATA section node is always a leaf node so you will find it as a
child nodes of element nodes. You can also use XPath where supported to
find the CDATA section node, XPath does not distinguish between text
nodes and CDATA section nodes, both are selected by the XPath text().
So grab the CDATA section node and put its nodeValue as the innerHTML of
a HTML div e.g.
divElement.innerHTML = cdataSectionNode.nodeValue;
 
J

Julian Turner

Pugi! said:
Using AJAX I want to send some information from the server (php-page)
as XML to the client. The contents can be very divers so I have to use
XML instead of text. On one occasion the contents is html, I can put
this in a CDATA section with PHP, but how do I retrieve that
information with Javascript and put the HTML in a div ?

thanx,

Pugi!

Hi

Assuming you are using XMLHttpRequest, a common approach is:-

1. Get the XMLDocument from the "responseXML" property.

2. Use DOM objects and methods (document.firstChild etc) to get to the
CDATASection in the node tree, and "nodeValue" to extract its contents.

3. Use "innerHTML" to put the contents in a div.

There are lots of libraries to choose from that offer to do this for
you, as a small amount of Google searching will show. Sarissa is one
such example.

Regards

Julians
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,836
Messages
2,569,750
Members
45,545
Latest member
rapter____0

Latest Threads

Top