node.js中怎么实现前后台交互功能
短信预约 -IT技能 免费直播动态提醒
node.js中怎么实现前后台交互功能,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
执行过程为:
(1)在浏览器地址栏输入网址,向node服务器发送HTML请求;服务器接到请求后,返回一个HTML文件给客户端;
(2)客户端浏览器对HTML进行渲染,遇到<script>标签后,再次向服务器请求,服务器响应一个JavaScript文件给客户端,
(3)客户端浏览器对JavaScript文件进行渲染,渲染过程中,如果遇到ajax请求,客户端还会向服务器进行请求,服务器仍然会响应浏览器。
(4)最后,浏览器把渲染好的网页呈现在浏览者面前。
1、HTML部分:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>客户管理系统</title>
</head>
<body>
<div class="box">
<a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="link">NEW CUSTOMER</a>
<h3>
<span class="fir">ID</span>
<span>NAME</span>
<span class="fir">AGE</span>
<span>PHONE</span>
<span>ADDRESS</span>
<span>CONTROL</span>
</h3>
<ul id="conList">
<li>
<span class="fir">1</span>
<span>钱成</span>
<span class="fir">25</span>
<span>13044086186</span>
<span>Bei Jing</span>
<span class="control">
<a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" >修改</a>
<a href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" >删除</a>
</span>
</li>
</ul>
</div>
<script charset="utf-8" type="text/javascript" class="lazy" data-src="js/ajax.js"></script>
<script charset="utf-8" type="text/javascript" class="lazy" data-src="js/index.js"></script>
</body>
</html>
2、ajax部分:
~function () {
//->createXHR:创建AJAX对象,兼容所有的浏览器
function createXHR() {
var xhr = null,
flag = false,
ary = [
function () {
return new XMLHttpRequest;
},
function () {
return new ActiveXObject("Microsoft.XMLHTTP");
},
function () {
return new ActiveXObject("Msxml2.XMLHTTP");
},
function () {
return new ActiveXObject("Msxml3.XMLHTTP");
}
];
for (var i = 0, len = ary.length; i < len; i++) {
var curFn = ary[i];
try {
xhr = curFn();
createXHR = curFn;
flag = true;
break;
} catch (e) {
}
}
if (!flag) {
throw new Error("your browser is not support ajax,please change your browser,try again!");
}
return xhr;
}
//->ajax:实现AJAX请求的公共方法;
function ajax(options) {
var _default = {
url: "",
type: "get",
dataType: "json",
async: true,
data: null,
getHead: null,
success: null
};
for (var key in options) {
if (options.hasOwnProperty(key)) {
_default[key] = options[key];
}
}
if (_default.type === "get") {
_default.url.indexOf("?") >= 0 ? _default.url += "&" : _default.url += "?";
_default.url += "_=" + Math.random();
}
//->SEND AJAX
var xhr = createXHR();
xhr.open(_default.type, _default.url, _default.async);
xhr.onreadystatechange = function () {
if (/^2\d{2}$/.test(xhr.status)) {
if (xhr.readyState === 2) {
if (typeof _default.getHead === "function") {
_default.getHead.call(xhr);
}
}
if (xhr.readyState === 4) {
var val = xhr.responseText;
if (_default.dataType === "json") {
val = "JSON" in window ? JSON.parse(val) : eval("(" + val + ")");
}
_default.success && _default.success.call(xhr, val);
}
}
};
xhr.send(_default.data);
}
window.ajax = ajax;
}();
3、JavaScript部分:
var customer = (function () {
var conList = document.getElementById('conList');
function bindEvent() {
conList.onclick = function (ev) {
ev = ev || window.event;
var tar = ev.target || ev.class="lazy" data-srcElement,
tarTag = tar.tagName.toUpperCase(),
tarInn = tar.innerHTML;
if (tarTag === 'A' && tarInn === '删除') {
//->ALERT、CONFIRM、PROMPT
var cusId = tar.getAttribute('data-id'),
flag = window.confirm('确定要删除编号为 [ ' + cusId + ' ] 的客户吗?');
if (flag) {//->点击的是确定按钮:调取对应的API接口实现删除即可
ajax({
url: '/removeInfo?id=' + cusId,
cache: false,
success: function (result) {
if (result && result.code == 0) {
//->删除成功后在HTML结构中移除对应的LI标签
conList.removeChild(tar.parentNode.parentNode);
}
}
});
}
}
}
}
function bindHTML(data) {
var str = '';
for (var i = 0; i < data.length; i++) {
var cur = data[i];
str += '<li>';
str += '<span class="fir">' + cur.id + '</span>';
str += '<span>' + cur.name + '</span>';
str += '<span class="fir">' + cur.age + '</span>';
str += '<span>' + cur.phone + '</span>';
str += '<span>' + cur.address + '</span>';
str += '<span class="control">';
str += '<a href="add.html?id=' + cur.id + '" rel="external nofollow" >修改</a>';
str += '<a href="javascript:;" rel="external nofollow" data-id="' + cur.id + '">删除</a>';
str += '</span>';
str += '</li>';
}
conList.innerHTML = str;
}
return {
init: function () {
ajax({
url: '/getAllList',
type: 'GET',
dataType: 'JSON',
cache: false,
success: function (result) {
if (result && result.code == 0) {
bindHTML(result.data);
bindEvent();
}
}
});
}
}
})();
customer.init();
4、node服务器部分:
var http = require("http");
var url = require("url");
var fs = require("fs");
var server1 = http.createServer(function (request, response) {
var urlObj = url.parse(request.url, true);
var pathname = urlObj.pathname;
var query = urlObj.query;
var reg = /\.(HTML|CSS|JS|ICO)/i;
if (reg.test(pathname)) {
var suffix = reg.exec(pathname)[1].toUpperCase();
var suffixMIME = suffix === 'HTML' ? 'text/html' : (suffix === 'CSS' ? 'text/css' : 'text/javascript');
try {
var conFile = fs.readFileSync('.' + pathname, 'utf-8');
response.writeHead(200, {'content-type': suffixMIME + ';charset=utf-8;'});
response.end(conFile);
//以conFile结束向客户端的响应,即给客户端返回./index.html的全部代码,供客户端渲染成页面。
} catch (e) {
response.writeHead(404, {'content-type': 'text/plain;charset=utf-8;'});
response.end('request file is not found!');
}
return;
}
//->数据API请求处理:客户端的JS代码中我们通过AJAX向服务器发送的请求,服务器接收到请求并且
// 获取客户端传递的数据,把需要的数据内容准备好,然后在返回给客户端,客户端在AJAX的READY
// STATE等于4的时候获取返回的内容(都是按照API的规范文档来处理)
var customData = fs.readFileSync('./json/custom.json', 'utf-8');
customData.length === 0 ? customData = '[]' : null;
customData = JSON.parse(customData);
var result = {
code: 1,
msg: '失败',
data: null
};
var customId = null;
//1)获取所有的客户信息
if (pathname === '/getAllList') {
if (customData.length > 0) {
result = {
code: 0,
msg: '成功',
data: customData
};
}
response.writeHead(200, {'content-type': 'application/json;charset=utf-8;'});
response.end(JSON.stringify(result));
return;
}
//2)获取指定的客户信息
if (pathname === '/getInfo') {
customId = query['id'];
customData.forEach(function (item, index) {
if (item['id'] == customId) {
result = {
code: 0,
msg: '成功',
data: item
};
}
});
response.writeHead(200, {'content-type': 'application/json;charset=utf-8;'});
response.end(JSON.stringify(result));
return;
}
//3)增加客户信息
if (pathname === '/addInfo') {
var str = '';
request.on('data', function (chunk) {
str += chunk;
});
request.on('end', function () {
var data = JSON.parse(str);
data['id'] = customData.length === 0 ? 1 : parseFloat(customData[customData.length - 1]['id']) + 1;
customData.push(data);
fs.writeFileSync('./json/custom.json', JSON.stringify(customData), 'utf-8');
result = {
code: 0,
msg: '成功'
};
response.writeHead(200, {'content-type': 'application/json;charset=utf-8;'});
response.end(JSON.stringify(result));
});
return;
}
//4)修改客户信息
if (pathname === '/updateInfo') {
str = '';
request.on('data', function (chunk) {
str += chunk;
});
request.on('end', function () {
var data = JSON.parse(str),
flag = false;
for (var i = 0; i < customData.length; i++) {
if (data['id'] == customData[i]['id']) {
customData[i] = data;
flag = true;
break;
}
}
if (flag) {
fs.writeFileSync('./json/custom.json', JSON.stringify(customData), 'utf-8');
result = {
code: 0,
msg: '成功'
};
}
response.writeHead(200, {'content-type': 'application/json;charset=utf-8;'});
response.end(JSON.stringify(result));
});
return;
}
//5)删除客户信息
if (pathname === '/removeInfo') {
customId = query['id'];
var flag = false;
customData.forEach(function (item, index) {
if (item['id'] == customId) {
customData.splice(index, 1);
flag = true;
}
});
if (flag) {
fs.writeFileSync('./json/custom.json', JSON.stringify(customData), 'utf-8');
result = {
code: 0,
msg: '成功'
};
}
response.writeHead(200, {'content-type': 'application/json;charset=utf-8;'});
response.end(JSON.stringify(result));
return;
}
response.writeHead(404, {'content-type': 'text/plain;charset=utf-8;'});
response.end('request url is not found!');
});
server1.listen(80, function () {
console.log("server is success,listening on 80 port!");
});
看完上述内容,你们掌握node.js中怎么实现前后台交互功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注编程网行业资讯频道,感谢各位的阅读!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341