AJAX,带有节点js服务器 [英] AJAX, with node js server
问题描述
我想学习如何使用AJAX,比如说我想从我的html页面连接到node.js服务器.该页面上有一个按钮,当按一下我们向服务器发送请求时,服务器将发送回"hello world"字符串.
I would like to learn how to work with AJAX, let's say I want to connect to a node.js server, from my html page. The page has one button, when pressing that we send a request to the server, the server sends back a 'hello world' string.
我已经学习了如何制作html5页面以及如何启动node.js服务器
I have learned how to make a html5 page, and how to start a node.js server
一个简单的node.js服务器
A simple node.js server
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
这将打印出您好世界,这一切都很好.
This prints hello world, that's all good.
但是,如何才能使它在按下html页面上的按钮时被调用,该函数连接"或调用"服务器,并获得返回的字符串? 我有一本关于Node.js的书,但它没有提到AJAX,有没有更好的方法呢?
But, How can I make it so that when I press a button on a html page, a function is called, that 'connects' or 'calls' the server, and gets a string in return? I have a book on Node.js, but it says nothing about AJAX, is there a better way to do it?
我很乐意提供帮助!
推荐答案
AJAX
调用需要从客户端(即浏览器)启动.
您的node.js
应用程序将收到一个请求,进行处理,然后将响应返回给客户端
AJAX
call needs to be initiated from the client i.e. browser.
Your node.js
application than receives a request, handles it and returns response back to client
使用jQuery,它看起来像这样:
using jQuery it would look like this:
$.get( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
这篇关于AJAX,带有节点js服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!