<!doctype> <html> <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>
let http = require('http');
let qs = require('querystring');
let server = http.createServer(function(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);
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');
xhr.send(val);
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有