Saturday, August 9, 2014

XMLHttpRequest, simple node and continuous updates.

Here is an example of node.js script:
var http = require('http'),
    fileSystem = require('fs');

function f(req, res) {
    var body = 'hello world';
    console.log(req.url);
    if (req.url == "/asdasd") 
    {
        res.writeHead(200, {
            'Content-Type': 'text/html' });
        filePath = "a.html";
        var readStream = fileSystem.createReadStream(filePath);
        readStream.pipe(res);
    }
    else
    {     
        var i = 0;
        res.writeHead(200, {
            'Content-Type': 'text/txt' });
        var idinterval;
        idinterval = setInterval( function()
        {
             res.write('Hello World');
             console.log("sent" + i);
             i+=1; 
             if(i==10)
             {
                  res.end();
                  clearInterval(idinterval);
             }
        }
        ,100);
    }
}
http.createServer(f).listen(1339, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1339/');

The idea here is to return a.html if 127.0.0.1:1339/asdasd is asked for, otherwise write Hello World and send them in .1 second intervals.

For a.html, I started with http://www.w3schools.com/ajax/ajax_example.asp and ended up with this:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
  var xmlhttp;
  xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=function()
  {
    document.getElementById("myDiv").innerHTML= xmlhttp.responseText;
  }
  
xmlhttp.open("GET","http://127.0.0.1:1339",true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="myDiv"><h2>Some text to be changed</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

What is the purpose of this? Well, to demonstrate you can send data over long lasting connection in xhr. Then you could split it in chunks and display it somehow, yet the solution is not very usable unless you are sending finite amount of data: the size of the responseText grows. There are some non-standard solutions for xhr for Firefox and could be for some later versions of Chrome, but as it stands xhr should not be used for this purpose without some improvements (like kill connection, for example).

Also xhr is limited to same origin policy: http://en.wikipedia.org/wiki/Same_origin_policy

The information is mostly duplication of things here: http://friendlybit.com/js/partial-xmlhttprequest-responses/

No comments:

Post a Comment