Created
May 13, 2012 04:36
-
-
Save devinrhode2/2681382 to your computer and use it in GitHub Desktop.
Streaming in html from an xhr...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var url = 'http://thescoutapp.com/idea/' | |
, xhr = new XMLHttpRequest(); | |
xhr.open('GET',url ,true); | |
xhr.onreadystatechange = function() { | |
if (xhr.readyState === 4) { | |
if (xhr.status === 200) { | |
var resp = xhr.responseText; | |
} else { | |
console.error('GET error for: ' + url); | |
console.error('xhr:'); | |
console.error(xhr); | |
} | |
} | |
} | |
xhr.send(); | |
var base64 = function (str) { | |
return window.btoa(unescape(encodeURIComponent(str))); | |
}; | |
var stack = ''; | |
var updatePage = function(code) { | |
if (once) { | |
console.log(curText); | |
once = false; | |
} else { | |
console.log(resp.substring(0, curText.length)); | |
console.error('\n||||||||||||||||||||||||||||||||||||||||||\n') | |
} | |
//stack += code; | |
//document.getElementById('smartframe').contentWindow.location.href = 'data:text/html;base64,' + base64(stack); | |
}; | |
var curText = '' | |
, once = true | |
, resp = ''; | |
setInterval(function(){ | |
resp = xhr.responseText; | |
if (resp && resp.length > 0) { | |
if (once) { | |
curText = resp; | |
updatePage(curText); | |
} else { | |
if (curText.length !== resp.length) { | |
//some damn assurance. | |
if (curText.length > resp.length) { | |
alert('HOLAY KAW! The response ended up *SHORTER* than the previously saved curText variable of itself. curText.length: ' + curText.length + ' resp.length: ' + resp.length); | |
} | |
//assure the begining is still the same (and we aren't confused) | |
if (curText !== resp.substring(0, curText.length)) { | |
alert('HOLY KAW! The beginning of the response got modified... somehow!. Check console.'); | |
console.error('curText and resp.substring(0, curText.length):', curText, resp.substring(0, curText.length)); | |
} | |
//Ok, granted things aren't fucked... if the response is longer than the curText, we should update the curText. | |
if (resp.length > curText.length) { | |
//things aren't fucked, so we can just flat out update the curText. | |
curText = resp; | |
updatePage(curText); | |
} | |
} | |
} | |
} | |
}, 3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment