Ciao,
in una piccola classe per il lancio di chiamate Ajax, un metodo chiama una funzione creata al volo, ma al suo interno viene perso il riferimento this alla classe.
Come posso richiamare il metodo XMLparse() per parsare il responso?
codice:
<html>
<head>
<script type="text/javascript">
<!--
function ajaxCall(URL) {
this.URL = URL;
this.XMLparse = function(XMLresponse) {
// parses the XML response and returns the HTML output string;
if (window.ActiveXObject) {
// MSIE:
var doc = new ActiveXObject("Microsoft.XMLDOM");
doc.async = "false";
doc.loadXML(XMLresponse);
} else {
// W3C compliant:
var parser = new DOMParser();
var doc = parser.parseFromString(XMLresponse, "text/xml");
}
var XMLdoc = doc.documentElement;
var value = XMLdoc.getElementsByTagName('value').item(0).firstChild.nodeValue;
return value;
};
this.createXmlHttp = function() {
var xmlHttp;
try {
// W3C compliant:
xmlHttp = new XMLHttpRequest();
return xmlHttp;
} catch(e) {
// MSIE:
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
return xmlHttp;
} catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
return xmlHttp;
} catch(e) {
alert("Your browser does not support AJAX.");
return false;
}
}
}
};
this.getResponse = function() {
var el = document.getElementById('result');
var xmlHttp = this.createXmlHttp();
xmlHttp.onreadystatechange = function() { // qui perdo il riferimento
document.getElementById('requestStatus').innerHTML = "Request status = " + xmlHttp.readyState;
if (xmlHttp.readyState == 4) {
document.getElementById('xmlHttpStatus').innerHTML = "HTTP status = " + xmlHttp.status;
el.innerHTML += this.XMLparse(xmlHttp.responseText);
}
}
var timestamp = new Date().getTime();
xmlHttp.open("GET", this.URL + "?request=" + timestamp, true);
xmlHttp.send(null);
};
}
var request = new ajaxCall("file.xml");
//-->
</script>
</head>
<body>
<div id="result"></div>
<div id="requestStatus"></div>
<div id="xmlHttpStatus"></div>
<input type="button" value="send request and parse" onclick="request.getResponse();" />
</body>
</html>
La JS console di Firefox dice:
Errore: this.XMLparse is not a function
Il file "file.xml" contiene un semplice campo:
codice:
<?xml version="1.0" encoding="UTF-8" ?>
<response>
<value>true</value>
</response>
[Il problema è sicuramente lì perché senza passare il responso al metodo XMLparse, questo viene visualizzato correttamente nel DIV apposito.]