samedi 9 mai 2015

Javascript make a post request and receive multiple responses

How can I receive multiple response from the server? The server sends to the client 3 different responses. Unfortunately my code catches only the first(I Think) one.

This is the index.html page with the javascript code:

<script type="text/JavaScript">
    console.log('begin');
    var http = new XMLHttpRequest();



    var data={
        'query'        : "test"
    }


    data=JSON.stringify(data);


    http.open("POST", "http://localhost:8080", true);

    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");


    http.onreadystatechange = function() {
        console.log('onreadystatechange');
        if (http.readyState == 4 && http.status == 200) {
            console.log(http.responseText);
        }
        else {
            console.log('readyState=' + http.readyState + ', status: ' + http.status);
        }
    }

    console.log('sending...')
    http.send(data);
    console.log('end');

</script>

In NODE JS I can catch all the responses in this way... is there something similar?

var options = {
    host: 'localhost',
    port: 8080,
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length
    }
};

var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

Aucun commentaire:

Enregistrer un commentaire