Problem Statement : If your Widget is connecting to a remote HTML-site through XMLHttpRequest(), the function responseXML will not work, as the response is not pure XML. Thus the following example is showing a smooth solution on how to deal with this problem and parse the HTML as it was an XML tree.
The code shows a basic Widget, that connects to a remote (or a local file for debug reasons) HTML-Site and parses the content. As the returned HTML-Code is not XML-well formed the 'responseText()' method is used to retrieve the plain HTML-Code as text, which then is assigned to a dynamically created div using 'document.createElement('div');'
You can download the full Widget here.
To connect to a remote site, you can use this code snippet:
// defined global, as required in call-back as well.
var xmlHttp = null;
function openConnection()
{
try{
// create a new connection object
xmlHttp = new XMLHttpRequest();
// reference to Call-Back Function;
xmlHttp.onreadystatechange = httpCallBack;
// url you connect to; can also be a local file
var url_frame = "local.txt";
// open the URL now
xmlHttp.open('GET', url_frame, true);
// and send GET request
xmlHttp.send(null);
}
catch(e)
{
}
}
Asynchronously (that's the first 'A' in AJAX ;-) the Call-Back function 'httpCallBack' of the Widget is called
// Call-Back Function for the XMLHttpRequest() Request
function httpCallBack()
{
if(xmlHttp.readyState != 4)
{
// tell the user, that the your widget is still
// waiting for the response to be completed
}
// readyStatus=4 Means completed
if (xmlHttp.readyState == 4) {
// get HTTP Data
try
{
// first check, if there is a response at all
var resultXml = xmlHttp.responseText;
if(!resultXml)
// put some error message here. "repsonseText Failed or alike";
else
{
// now create a new div (actually a node!) dynamically
// and do some assignments of parameters
var newdiv = document.createElement('div');
newdiv.setAttribute('id','temp');
// put the response of the Site into this div
// this allows us to treat the result as a node and therefore
// use eg 'getElementsByTagName' on the HTML, that is not XML
// conform! That's a very nice thing to do for that purpose.
newdiv.innerHTML = xmlHttp.responseText;
// now you can parse your content as you like using the HTML Code
// as XML structure
// eg: newdiv.getElementsByTagName("td");
}// end-else
} // end-try
catch (e) {
// do some exception handling here.
}
}
}
No related wiki articles found