Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Streaming JSON fragments to jquery

Tags:

jquery

http

Is it possible to use jquery to hold open an HTTP connection and stream in data?

From my web server, I get the following (each JSON object is separated by a newline)

HTTP/1.1 200 OK
Content-Type: text/plain
Transfer-Encoding: chunked

{"a":{"uptime":15876}}
{"a":{"uptime":15877}}
{"a":{"uptime":15878}}
{"a":{"uptime":15879}}
...

In my web page I'm doing:

$.ajax({
        type:       "GET",
        url:        'http://server/stream',
        data:       function(data) { console.log("data="+data); },
        timeout:    20000,
        dataType:   "text",
        error:      function(XMLHttpRequest, textStatus, errorThrown) { console.log(textStatus); },
        success:    function(data) {console.log("done"+data); },
        cache:      false
    });

I see no output and Firebug claims that there was no response to the HTTP request, I see a spinner in the Firefox tab.

tcpdump shows that data is being received by the browser, but I never see any console logs, almost as if it's all being buffered away for printing on completion.

What am I missing?

like image 417
Joby Taffey Avatar asked Jun 09 '11 20:06

Joby Taffey


1 Answers

What you are trying to do is considered long polling. It's not readily achievable with jquery, what you may want to look at, and this might be overkill, is a non-blocking server tech like node.js with that you could use this plugin with jQuery.

like image 159
Jeremy B. Avatar answered Oct 06 '22 22:10

Jeremy B.