您好,登錄后才能下訂單哦!
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" 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 (/^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.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中怎么實現前后臺交互功能的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。