Download presentation
Presentation is loading. Please wait.
1
Ajax with XML 23-Feb-19
2
Displaying theAjax response
Here is the previous code for dealing with a non-XML response: function alertContents(http_request) { if (http_request.readyState == 4) { if (http_request.status == 200) { alert(http_request.responseText); } else { alert('There was a problem with the request.'); } } }
3
Doing it with XML Here’s an XML file named test.xml: <?xml version="1.0" ?> <root> I'm a test. </root> function alertContents(http_request) { if (http_request.readyState == 4) { if (http_request.status == 200) { var xmldoc = http_request.responseXML; var root_node = xmldoc.getElementsByTagName('root').item(0); alert(root_node.firstChild.data); } else { alert('There was a problem with the request.'); } } }
4
responseText and responseXML
The Content-Type in the header tells the type of server response For non-XML, you can use text/html or text/plain For sending XML, it's better to use text/xml When the server sends text/xml, the browser parses it, creates an XML DOM tree, and places this tree in the responseXML object The XML is also available in the responseText object, but it you use this you will have to parse it yourself
5
HTML DOM vs. XML DOM The DOM for the web page represents HTML
The DOM for the XML represents the server's response They have the same methods!
6
Sending XML to the server
The server is really good at handling name-value pairs If you want to send XML... It pretty much has to be sent as POST XML gets long very quickly All those special characters need to be URL-encoded You have to setRequestHeader("Content-Type", "text/xml") The server doesn't have DOM trees--you will have to parse the XML yourself Bottom line: Sending XML to the server is too much work!
7
XML notes The XML response object supports very complete XML DOM processing The response header must include: Content-Type: text/xml or IE will throw an “Object expected” JavaScript error Cache-Control: no-cache or the response will be cached and the request will never be resubmitted For some browsers you may need to do request.overrideMimeType('text/xml'); In Firefox, this will give an error if the response isn’t valid XML
8
The End
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.