【nodeJs】用nodeJs实现一个简单的前后端交互的例子

实现效果图:

这里写图片描述

Ajax知识补充:

1,创建XMLHttpRequest对象:

var xmlHttp = new XMLHttpRequest();

2, 向服务器发送请求:

xmlHttp.setRequestHeader(header,value)  //向请求添加http头
xmlHttp.open(method, url, async)  //async:true(异步) false(同步)
xmlHttp.end(string)   //string仅用于POST请求

3, 服务器响应

获得来自服务器的响应,可以使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性。
responseText 获得字符串形式的响应数据。
responseXML 获得 XML 形式的响应数据。
4, onreadystatechange 事件。
每当 readyState 改变时,就会触发onreadystatechange 事件。
readyState 属性存有 XMLHttpRequest 的状态信息。
readyState

存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪

HTML代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <input type="text" id="username" placeholder="请输入用户名">
    <button id="bt">提交</button>
    <h1 id="test"></h1>

    <script src="index.js"></script>
</body>

</html>

index.js

var test = document.getElementById('test');
var bt = document.getElementById('bt');

bt.onclick = function () {
    var value = document.getElementById('username').value;
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange=function()
    {
        if (xmlHttp.readyState==4 && xmlHttp.status==200)
        {
            test.innerHTML = xmlHttp.responseText;
        }
    };

    xmlHttp.open('POST', 'http://127.0.0.1:3000/', true); 
    xmlHttp.send(value);      //吧input框中的value发送过去
};

app.js

var http = require('http');

var server = http.createServer(function (req, res) {
    var body = '';
    req.on('data', function(data) {      // 接收客户端发送过来的数据, 也就是 xmlHttp.send(value);
        body += data;
    });

    req.on('end', function() {
        res.writeHeader(200, {
            'Content-Type': 'text/plain',
            'Access-Control-Allow-Origin': '*'    //解决跨域问题
        });
        res.write("hello:" + body);
        res.end();
    })
});

server.listen(3000, function () {
    console.log('server start at localhost:3000');
});


执行node app.js   然后在html页面中输入用户名,点击之后就可以看到后端返回的值了

猜你喜欢

转载自blog.csdn.net/ac_greener/article/details/80468555