XMLHttpRequest read progressive data not working?
I'm having issues with XMLHttpRequest downloading progressive data. I get a st开发者_StackOverflow社区ate 2 and than state 3. After state 3 it never gets called again. What am I doing wrong? I read somewhere I need to flush the data but how do I do that?
Here is my code:
var xmlHttp = new XMLHttpRequest();
// try to connect to the server
try
{
// initiate server request
xmlHttp.open("GET", "http://208.43.121.133:8164/;", true);
xmlHttp.setRequestHeader("Icy-Metadata", "1");
xmlHttp.onreadystatechange = function()
{
alert("status: "+xmlHttp.status);
alert("State: "+xmlHttp.readyState);
if (xmlHttp.readyState == 3)
{
alert(xmlHttp.responseText);
}
};
xmlHttp.send(null);
}
// display an error in case of failure
catch (e)
{
alert("Can't connect to server:\n" + e.toString());
}
am I allowed to read the xmlHttp.responseText when readyState is 3?
The problem is most likely with this segment:
if(xmlHttp.readyState == 3) {
alert(xmlHttp.responseText);
}
The reason being is that the xmlRequest isn't complete yet (readyState=4 when complete). When you requested the responseText prematurely, it triggered an error and stopped the code from finishing.
So you would change it to:
if(xmlHttp.readyState == 4) {
alert(xmlHttp.responseText);
}
Kranu is correct, you're not allowed to read responseText when readyState is 3. See http://www.davidflanagan.com/2005/08/xmlhttprequestreadystate-3.html
The solution is to send a message at a time. When you receive one message, just make another XHR. That's how google does (did?) server push.
精彩评论