js ajax send,javascript - Basic Ajax send/receive with node.js - Stack Overflow

Your request should be to the server, NOT the server.js file which instantiates it. So, the request should look something like this: xmlhttp.open("GET","http://localhost:8001/", true); Also, you are trying to serve the front-end (index.html) AND serve AJAX requests at the same URI. To accomplish this, you are going to have to introduce logic to your server.js that will differentiate between your AJAX requests and a normal http access request. To do this, you'll want to either introduce GET/POST data (i.e. call http://localhost:8001/?getstring=true) or use a different path for your AJAX requests (i.e. call http://localhost:8001/getstring). On the server end then, you'll need to examine the request object to determine what to write on the response. For the latter option, you need to use the 'url' module to parse the request.

You are correctly calling listen() but incorrectly writing the response. First of all, if you wish to serve index.html when navigating to http://localhost:8001/, you need to write the contents of the file to the response using response.write() or response.end(). First, you need to include fs=require('fs') to get access to the filesystem. Then, you need to actually serve the file.

XMLHttpRequest needs a callback function specified if you use it asynchronously (third parameter = true, as you have done) AND want to do something with the response. The way you have it now, string will be undefined (or perhaps null), because that line will execute before the AJAX request is complete (i.e. the responseText is still empty). If you use it synchronously (third parameter = false), you can write inline code as you have done. This is not recommended as it locks the browser during the request. Asynchronous operation is usually used with the onreadystatechange function, which can handle the response once it is complete. You need to learn the basics of XMLHttpRequest. Start

Here is a simple implementation that incorporates all of the above:

server.js:

var http = require('http'),

fs = require('fs'),

url = require('url'),

choices = ["hello world", "goodbye world"];

http.createServer(function(request, response){

var path = url.parse(request.url).pathname;

if(path=="/getstring"){

console.log("request recieved");

var string = choices[Math.floor(Math.random()*choices.length)];

console.log("string '" + string + "' chosen");

response.writeHead(200, {"Content-Type": "text/plain"});

response.end(string);

console.log("string sent");

}else{

fs.readFile('./index.html', function(err, file) {

if(err) {

// write an error response or nothing here

return;

}

response.writeHead(200, { 'Content-Type': 'text/html' });

response.end(file, "utf-8");

});

}

}).listen(8001);

console.log("server initialized");

frontend (part of index.html):

function newGame()

{

guessCnt=0;

guess="";

server();

displayHash();

displayGuessStr();

displayGuessCnt();

}

function server()

{

xmlhttp = new XMLHttpRequest();

xmlhttp.open("GET","http://localhost:8001/getstring", true);

xmlhttp.onreadystatechange=function(){

if (xmlhttp.readyState==4 && xmlhttp.status==200){

string=xmlhttp.responseText;

}

}

xmlhttp.send();

}

You will need to be comfortable with AJAX. Use the mozilla learning center to learn about XMLHttpRequest. After you can use the basic XHR object, you will most likely want to use a good AJAX library instead of manually writing cross-browser AJAX requests (for example, in IE you'll need to use an ActiveXObject instead of XHR). The AJAX in jQuery is excellent, but if you don't need everything else http://microjs.com/. You will also need to get comfy with the node.js docs, found http://google.com for some good node.js server and static file server tutorials. http://nodetuts.com is a good place to start.

UPDATE: I have changed response.sendHeader() to the new response.writeHead() in the code above !!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值