原生node.js案例--前后台交互
本案例包含4部分:(1)HTML部分;(2)ajax部分;(3)JavaScript部分;(4)node服务器部分。另外,因为牵涉到服务器,所以这里没法“效果预览”。
执行过程为:
(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> <h2> <span class="fir">ID</span> <span>NAME</span> <span class="fir">AGE</span> <span>PHONE</span> <span>ADDRESS</span> <span>CONTROL</span> </h2> <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" src="js/ajax.js"></script> <script charset="utf-8" type="text/javascript" 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 (/^2d{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.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 websocket使用socket.io库实现实时聊天室
认识websocketWebSocketprotocol是HTML5一种新的协议。它实现了浏览器与服务器全双工通信(full-duple)。一开始的握手需要借助HTTP请求完成。其实websocket并不是很
Node.js获取前端ajax提交的request信息
今天看一下Node.js怎么获取ajax提交的request信息众所周知,ajax可以在不刷新整个页面的情况下实现局部刷新,这是相当好的一种方式,能够让我们动态更
从零学习node.js之模块规范(一)
什么是Node.js很多初学者并没有真正地理解Node.js到底是什么。nodejs.org网站中的描述也没有多大帮助。首先要清楚Node不是一个Web服务器,这十分重要。它