topical media & game development
professional-ria-03-XMLQueryExample2.htm / htm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Example XML Query and Response Parse</title>
<link rel=StyleSheet href="../../stylesheets/RIAStyle1.css" TYPE="text/css">
<script src="../../scripts/xmlw3cdom.js" type="text/javascript"> </script>
<script src="../../scripts/xmlsax.js" type="text/javascript"> </script>
<script type="text/javascript">
//<![CDATA[
var xmlhttp = false;
function queryHandler(target) {
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
} catch (e) {
}
if(target !== ""){
var url = '../../phpscripts/xmlQuery.php?' + target;
xmlhttp.open('GET', url, true);
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('Result').innerHTML = '';
document.getElementById('State').innerHTML = '';
var cleanXMLText = cleanupResponseString(xmlhttp.responseText);
// if (xmlhttp.responseText != null) {alert("NON-null responseText:"+ xmlhttp.responseText);}else {alert("NULL responseText");}
parseResult(cleanXMLText);
document.getElementById("State").innerHTML = dump(xmlhttp.responseXML.childNodes,"Response...<br/>","<br/>"," ",5);
// ALTparseResult(xmlhttp);
} else {
document.getElementById('State').innerHTML = "Loading...";
}
};
xmlhttp.send(null);
}
}
function cleanupResponseString(response){
return response.slice(response.indexOf("<"), response.lastIndexOf(">")+1);
}
function ALTparseResult(req){
var docRoot = req.responseXML.documentElement;
if (docRoot != null) {alert("NON-null docRoot:"+ docRoot);}else {alert("NULL docRoot");}
// document.getElementById("Title").innerHTML = docRoot.getElementsByTagName('Title')[0].firstChild.data;
}
// ...
function dump(theItem,theItemName,recDelim,aNester,
howDeep,begString,endString) {
dumpDepthCount = 0;
maxDumpDepth = 5;
newline = "";
nester = "";
debugString = "";
if (howDeep) {
if (howDeep > maxDumpDepth) {
keepItUp = confirm(
"The debugging function dump() is being called with a greater nest level than is recommended.\nThis may take a while, and it may error out or crash your browser.\nContinue?");
if (!keepItUp) {
return;
}
}
maxDumpDepth = howDeep;
}
recDelim ? newline = recDelim : newline = '\n';
aNester ? nester = aNester : nester = '\t';
function indent() {
var retVal = "";
for (var i=dumpDepthCount; i>1; i--) {
retVal += nester;
}
return retVal;
}
function asdlkasf(theItem,theItemName) {
dumpDepthCount++;
if (dumpDepthCount >= maxDumpDepth) {
dumpDepthCount--;
return;
}
var itemType = typeof theItem;
switch(itemType) {
case "number":
case "boolean":
debugString += indent() + theItemName +
', a ' + itemType + ': ' +
theItem.toString().toLowerCase() + newline;
break;
case "string":
debugString += indent() + theItemName +
", a string: '" + theItem + "'" + newline;
break;
case "function":
if (theItem.toString().indexOf(
'native code]') == -1) {
indentStr = newline+indent();
debugString += indent() + theItemName +
', a function: ' +
theItem.toString().replace(
/(\\n|\<br\>)/g, indentStr) +
newline;
}
break;
case "object":
try {
debugString += indent() + theItemName +
', an object' + newline;
for (att in theItem) {
if (att && att != "undefined" &&
theItem[att] &&
theItem[att] != "undefined" &&
att != 'parentNode' &&
att != 'offsetParent' &&
att != 'ownerDocument' &&
att != 'nextSibling' &&
att != 'previousSibling') {
asdlkasf(theItem[att],att) +
newline;
}
}
} catch (ex) {
debugString += indent() + "(" + att +
" inaccessible as object attribute)"
+ newline;
}
try {
if (theItem[0]) {
debugString += indent() + theItemName
+ ', an array' + newline;
dumpDepthCount++;
for (var i=0;i<theItem.length;i++) {
if (theItem[i]) {
if (theItem[i] &&
theItem[i] != "undefined") {
debugString += indent() +
"Index " + i + newline;
asdlkasf(theItem[i],i) +
newline;
}
}
}
dumpDepthCount--;
}
} catch (ex) {
debugString += indent() + "(Index " + i
+ " inaccessible as array element)"
+ newline;
}
break;
case "undefined":
debugString += indent() +
"(type undefined)";
break;
}
dumpDepthCount--;
}
if (begString && begString.length > 0) {
debugString += begString;
}
asdlkasf(theItem,theItemName,recDelim,aNester);
if (endString && endString.length > 0) {
debugString += endString;
}
return debugString;
}
// ...
function parseResult(xml) {
//instantiate the W3C DOM Parser
var parser = new DOMImplementation();
//load the XML into the parser and get the DOMDocument
var domDoc = parser.loadXML(xml);
//get the root node (in this case, it is ResultSet)
var docRoot = domDoc.getDocumentElement();
// alert("parseResult doc Root: "+docRoot);
//display the data
document.getElementById("Title").innerHTML = docRoot.getElementsByTagName("Title").item(0).getFirstChild().getNodeValue();
if (docRoot.getElementsByTagName("Summary").item(0).getFirstChild() != null){
document.getElementById("Summary").innerHTML =
docRoot.getElementsByTagName("Summary").item(0).getFirstChild().getNodeValue();
} else {
document.getElementById("Summary").innerHTML = "No Summary";
}
// heree we are getting an attribute of ResultSet, not a node; thus a somewhat different strategy ...
var totalHits = docRoot.getAttributeNode("totalResultsAvailable").getNodeValue()
document.getElementById("TotalHits").innerHTML = totalHits;
document.getElementById("PictureHeader").innerHTML = "<p>an Example Picture</p>";
document.getElementById("PictureURL").innerHTML =
"<img src=\""+
docRoot.getElementsByTagName("ClickUrl").item(0).getFirstChild().getNodeValue() +
"\" alt=\""+
docRoot.getElementsByTagName("ClickUrl").item(0).getFirstChild().getNodeValue() +
"\"/>"
;
document.getElementById("State").innerHTML = "";
} // end function parseResult
function onLoad() {
//TODO Lock HTTP requests against each other...
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
xmlhttp.overrideMimeType('text/xml');
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function doQuery() {
var query = document.getElementById("imageQuery").value;
var uri = "http://api.search.yahoo.com/ImageSearchService/V1/imageSearch?appid=YahooDemo&query="+query+"&results=1&output=xml";
queryHandler(uri);
}
//]]>
</script>
</head>
<body onload="onLoad()">
<div id="header">
<h1>Simple XML DOM Query and Parsing Sample </h1>
<h2>
Use a JavaScript call to directly invoke RESTFul Service.
Get the response back as a XML Object. Parse the XML to get Tags, tag attributes
and the value of the nodes delimited by tags..
</h2>
</div>
<br />
<div class="inputelement"><button onClick="doQuery()">Image Search Term</button>
<input id="imageQuery" value="Rose" size="50"></input>
</div>
<br />
<div id="State"></div>
<div id="Result"></div>
<p>TotalHits: <span id="TotalHits" style="font-weight:bold"></span> </p>
<p>Title: <span id="Title" style="font-weight:bold"></span> </p>
<p>Summary: <span id="Summary" style="font-weight:bold"></span> </p>
<span id="PictureHeader" class="pictureHeader"></span>
<span id="PictureURL"></span>
</body>
</html>
(C) Æliens
20/2/2008
You may not copy or print any of this material without explicit permission of the author or the publisher.
In case of other copyright issues, contact the author.