I’m trying to create a piece of Javascript that connects to the server, receives a response and then automatically connects again.
<head>
<title>tests</title>
<script type="text/javascript" src="/javascripts/jquery.min.js"></script>
<script type="text/javascript">
function requestData() {
var oRequest = new XMLHttpRequest();
oRequest.onreadystatechange = handleData;
oRequest.open( 'GET', '/test.php', true );
oRequest.send( null );
}
function handleData() {
if( this.readyState == 4 ) {
document.write( this.responseText );
requestData();
}
}
$(function(){
requestData();
});
</script>
</head>
<body>
</body>
The code above works fine in chrome but after two requests the script fails in Firefox with the following error…
requestData is not defined
Does anyone know why this is happening? The server is only responding with single digit numbers at the moment. (PS I know this doesn’t work in IE, thats fine)
Thanks
I assume that two requests is as long as it takes Firefox to finish processing the document and close it. This means that when
document.writeis called again, it automatically callsdocument.openand trashes the existing document, including the scripts, so the function gets deleted.Use DOM manipulation instead of
document.write.