Breaking down the solution
- The issue at hand
- Why it's not a major concern
- Identifying the root of the problem
- Steps to pinpoint the cause
- A comprehensive solution with error handling
The issue at hand
An error arises due to the attempt to interpret ContentRight.html
as an XML file. Given the strict nature of XML files, even minor discrepancies like a missing </img>
tag can lead to a complete failure. The presence of multiple top-level elements is the specific issue here, with the second element being flagged as "Junk after document element," potentially because of an image tag.
Why it's not a major concern
However, the crux of the matter lies in the unnecessary XML parsing on the initial page load. Since you merely require the HTML content, the XML parsing seems superfluous. The error might cause responseXML
to be null, but utilizing responseText
ensures a smooth operation despite the error.
Identifying the root of the problem
Further analysis uncovers the core issue: the condition demanding HTTP status 200 with req.status == 200
. As the URL scheme is file://
rather than http://
, there won't be any status codes like error 500 or not found 404; instead, a value of 0
is returned, limiting your error diagnosis capabilities. In such scenarios, adding alert statements can provide useful insights.
Steps to pinpoint the cause
req.onreadystatechange = function() {
alert(req.readyState);
if (req.readyState == 4 && req.status == 200) {
document.getElementById(divId).innerHTML = req.responseText;
}
}
By alerting 1
, 2
, 3
, and 4
, you confirm the readyState
as 4. Subsequently, observing
req.onreadystatechange = function() {
if(req.readyState == 4)
alert(req.status);
if (req.readyState == 4 && req.status == 200) {
document.getElementById(divId).innerHTML = req.responseText;
}
}
and encountering the status 0
brings you closer to identifying the underlying issue.
A comprehensive solution with error handling
To address this, a well-rounded solution involves
req.onreadystatechange = function() {
if (req.readyState == 4 && (req.status == 200 || req.status == 0 && req.responseText)) {
document.getElementById(divId).innerHTML = req.responseText;
} else {
document.getElementById(divId).innerHTML = '<b>Error. HTTP ' + req.status + '</b>';
}
}
This solution accounts for a status of 0, possibly indicating connectivity issues where responseText
remains empty, resulting in 'Error. HTTP 0.' Conversely, in a file://
scenario, the script operates seamlessly. For server-related errors, an appropriate message like 'Error. HTTP 500' is displayed.