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.write
is called again, it automatically calls document.open
and trashes the existing document, including the scripts, so the function gets deleted.
Use DOM manipulation instead of document.write
.
If you use jquery, you should use $.ajax or something like that. It's easier to use and it works.
http://api.jquery.com/jQuery.ajax/
$.ajax({
url: 'http://my_url',
success: function (data) {
$.ajax({
url: 'http://my_url_2',
success: function (data) {
alert(data);
}
})
}
})
精彩评论