扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
node.js中怎么实现前后台交互功能,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
创新互联专注于企业网络营销推广、网站重做改版、防城港网站定制设计、自适应品牌网站建设、H5场景定制、商城系统网站开发、集团公司官网建设、成都外贸网站建设、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为防城港等各大城市提供网站开发制作服务。
执行过程为:
(1)在浏览器地址栏输入网址,向node服务器发送HTML请求;服务器接到请求后,返回一个HTML文件给客户端;
(2)客户端浏览器对HTML进行渲染,遇到
2、ajax部分: 3、JavaScript部分: 4、node服务器部分: 看完上述内容,你们掌握node.js中怎么实现前后台交互功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!~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;
}();
var customer = (function () {
var conList = document.getElementById('conList');
function bindEvent() {
conList.onclick = function (ev) {
ev = ev || window.event;
var tar = ev.target || ev.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 += '
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中怎么实现前后台交互功能
网页地址:http://kswjz.com/article/ggsdpp.html
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流