通过原生ajax与node实现交互
页面代码,index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>前后端简单交互</title>
</head>
<body>
<button id="btn1">food</button>
<button id="btn2">other</button>
<h1 id="content"></h1>
<script type="text/javascript" src="./client.js"></script>
</body>
</html>
服务端代码,client.js:
let btn1 = document.getElementById('btn1');
let btn2 = document.getElementById('btn2');
let content = document.getElementById('content');
btn1.addEventListener('click', function() {
ajax('POST', "http://127.0.0.1:3000/", 'name='+this.innerHTML);
});
btn2.addEventListener('click', function() {
ajax('POST', "http://127.0.0.1:3000/", 'name='+this.innerHTML);
});
// 封装的ajax方法
function ajax(method, url, val) { // 方法,路径,传送数据
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
content.innerHTML = xhr.responseText;
} else {
alert('Request was unsuccessful: ' + xhr.status);
}
}
};
xhr.open(method, url, true);
if(val) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); //设置POST 较常见表单的提交数据方式
}
xhr.send(val);
}
客户端代码:server.js
let http = require('http');
let qs = require('querystring');
let server = http.createServer(function(req, res) { //该函数用来创建一个HTTP服务器,并将 requestListener 作为 request 事件的监听函数。req请求对象,res响应对象
let body = ''; // 一定要初始化为"" 不然是undefined
req.on('data', function(data) {
body += data; // 所接受的Json数据
});
req.on('end', function() {
res.writeHead(200, { // 响应状态
"Content-Type": "text/plain", // 响应数据类型
'Access-Control-Allow-Origin': '*' // 允许任何一个域名访问
});
if(qs.parse(body).name == 'food') {
res.write('apple');
} else {
res.write('other');
}
res.end();
});
});
server.listen(3000);
运行: node server.js , 之后打开页面点击按钮就实现交互。