Nicholas Liao Nicholas Liao - 20 days ago 6
jQuery Question

How to set the argument "url" in xmlhttp.open() when I want to use Ajax to send/receive request with node.js

server.js can produce random number. So now I want to get a random number from the server and use xmlhttp to send a request. But the value of string is not changed when I load http://localhost:3000/index.html. What happen?

index.js is shown as follows:

$(document).ready(function() {
getRandomNum();
});

function getRandomNum() {
$(".button").each(function() {
var that = $(this);
that.click(function() {
var span = $("<span></span>").addClass("unread");
that.append(span);
span.text("...");
server(span);
});
});
}

function server(span) {
var string;
var xmlhttp = new XMLHttpRequest();
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
string = xmlhttp.responseText;
}
xmlhttp.open("GET","http://localhost:3000/", true);
xmlhttp.send();
span.text(string);
}


server.js is shown as follows:

var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');
var port = 3000;

http.createServer(function(req,res) {
var pathname = url.parse(req.url).pathname;
var mimeType = getMimeType(pathname);
if (!!mimeType) {
handlePage(req, res, pathname);
} else {
handleAjax(req, res);
}
}).listen(port, function(){
console.log('server listen on ', port);
});

function getMimeType(pathname) {
var validExtensions = {
".html" : "text/html",
".js": "application/javascript",
".css": "text/css",
".jpg": "image/jpeg",
".gif": "image/gif",
".png": "image/png"
};
var ext = path.extname(pathname);
var type = validExtensions[ext];
return type;
}

function handlePage(req, res, pathname) {
var filePath = __dirname + pathname;
var mimeType = getMimeType(pathname);
if (fs.existsSync(filePath)) {
fs.readFile(filePath, function(err, data){
if (err) {
res.writeHead(500);
res.end();
} else {
res.setHeader("Content-Length", data.length);
res.setHeader("Content-Type", mimeType);
res.statusCode = 200;
res.end(data);
}
});
} else {
res.writeHead(500);
res.end();
}
}

function handleAjax(req, res) {
var random_time = 1000 + getRandomNumber(2000);
var random_num = 1 + getRandomNumber(9);
setTimeout(function(){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("" + random_num);
}, random_time);
}

function getRandomNumber(limit) {
return Math.round(Math.random() * limit);
}

Answer

In your server(span) method, you initialize sending the request and immediately assigning the null string to the span by span.text(string) after this line xmlhttp.send();.

Once the response (random number) is received from the server, you are assigning the same to the variable string = xmlhttp.responseText; but not updating the same to the span.

Also, you haven't handled the response inside the onreadystatechange method.

I have modified your code below. I have created a test app and tested the same. Its working as you expected.

function server(span) {
            var string;
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange= function(){
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    string = xmlhttp.responseText;
                    span.text(string);
                }
            };
            xmlhttp.open("GET","http://localhost:3000/", true);
            xmlhttp.send();
        }