本文是一篇学习笔记,记录了学习express后台和ajax相关的知识
首先根据express建立一个服务器,用来模拟数据交互
安装express及相关依赖包 npm install express body-parser ejs —save
目录结构
RESTful/
--node_moudules/
--views/
--index.html
--main.js
--package.json
--server.js
初始化服务器
var express = require('express'); // 引入express
var bodyparser = require('body-parser'); // 引入body-parser中间件
var app = express(); // 生成一个express的实例
app.use(express.static(__dirname)); // 设置静态资源存放目录,这里就是当前文件下
app.use(bodyparser.json());
var PORT = process.env.PORT || 3000; // 设置express服务器的对外端口
var products = [{id:1,name:'alixwang'},{id:2,name:'zhangna'}]; // 模拟的数据库
/*
* 设置服务器监听端口
*/
app.listen(PORT,function(){
console.log('server setup in port '+PORT);
});
// 引入索引页面
app.get('/',function(req,res){
res.render('index.html');
});
索引页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>RESTful toturial by ajax</title>
<script src="main.js"></script>
<style>
body,div,h1,h2{
margin: 0;
}
.container{
width: 600px;
margin: 0 auto;
text-align: center;
}
.container h1{
background-color:#333;
color: #fff;
padding:20px 0;
}
.head{
margin-top: 30px;
width: 600px;
}
.head input{
width: 250px;
height: 30px;
font-size: 15px;
vertical-align: middle;
margin-right: 40px;
}
.head button{
width:80px;
height:35px;
margin-right: 20px;
border: 1px solid #ddd;
border-radius: 5px;
background:none;
}
.content{
padding: 40px 0;
margin-top: 20px;
background-color:#eee;
text-align: center;
}
.content table{
width: 500px;
margin: auto;
border-collapse: collapse;
}
.content table thead{
color: #666;
font-size: 20px;
}
.content table thead th{
width: 200px;
height: 30px;
line-height: 30px;
border-bottom: 1px solid #666;
}
.content table tbody td{
width: 200px;
height: 30px;
border-bottom: 1px dashed #666;
}
</style>
</head>
<body>
<div class="container">
<div class="head">
<h1>RESTful Toturial By Ajax</h1>
<hr>
<input type="text" id="productInput" placeholder="input product">
<button id="create_pro">create</button>
<button id="show_pro">show</button>
</div>
<div class="content">
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</body>
</html>
页面请求数据
// 构造的window.onlaod函数可以加载多个函数
function loadEvent(fn) {
var oldEvent = window.onload;
if (typeof window.onload != 'function') {
window.onload = fn;
} else {
window.onload = function () {
oldEvent();
fn();
}
}
}
// 事件触发函数,用来触发内置事件
function fireEvent(element,event){
if(window.createEventObject){
var evt = document.createEevntObject();
return element.fireEvent('on'+event,evt);
}else{
var evt = document.createEvent('HTMLevents');
evt.initEvent(event,true,true);
return !element.dispatchEvent(evt);
}
}
// 封装的ajax get方法
function getAjax(url, method) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
renderProd(JSON.parse(xhr.responseText));
}
}
xhr.open(method, url, true);
xhr.send();
console.log('bb');
}
// 封装的ajax post方法
function postAjax(url,method){
var val = document.getElementById('productInput').value;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
fireEvent(document.getElementById('show_pro'),'click');
}
}
xhr.open(method,url,true);
xhr.setRequestHeader('content-Type','application/json');
xhr.send(JSON.stringify({name:val}));
}
// 封装的ajax put 方法
function updateAjax(url,method,data){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
}
}
xhr.open(method,url,true);
xhr.setRequestHeader('content-Type','application/json');
xhr.send(data);
}
// 封装的ajax delete方法
function deleteAjax(url,method,data){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
}
}
xhr.open(method,url,true);
xhr.setRequestHeader('content-Type','application/json');
xhr.send(data);
}
// 用来展示从服务取得的数据,其中用了ES6的格式化字符串
function renderProd(data) {
console.log(data);
var tbody = document.getElementsByTagName('tbody')[0];
var str = '';
for (var i = 0; i < data.products.length; i++) {
str += `<tr><td>${data.products[i].id}</td><td><input type="text" value='${data.products[i].name}' /></td><td><button name='${data.products[i].name}'>Updata</button><button name='${data.products[i].name}'>Delete</button></td></tr>`
}
tbody.innerHTML = str;
}
// 封装的事件添加方法
function addEvent(elem,type,handle){
if(window.addEventListener){
elem.addEventListener(type,handle,false);
}else if(window.attachEvent){
elem.attachEvent('on'+type,handle);
}else{
elem['on'+type] = handle;
}
}
/*
* 下面四个函数分别是展示、创建、更行、删除的对应事件绑定,和ajax方法的调用
*/
function showProd(){
console.log('aa');
var btn = document.getElementById('show_pro');
addEvent(btn,'click',function(){
getAjax('/products','GET');
});
}
function createProd(){
var btn = document.getElementById('create_pro');
addEvent(btn,'click',function(){
postAjax('/products','POST');
});
}
function updateProd(){
var table = document.getElementsByTagName('table')[0];
addEvent(table,'click',function(e){
var event = e || window.event;
if(event.target.innerHTML === 'Updata'){
var id = event.target.parentNode.parentNode.getElementsByTagName('td')[0].innerHTML;
var name = event.target.parentNode.previousSibling.getElementsByTagName('input')[0].value;
console.log(id,name);
var data = JSON.stringify({id:id,name:name});
updateAjax('/products','PUT',data);
}
})
}
function deleteProd(){
var table = document.getElementsByTagName('table')[0];
addEvent(table,'click',function(e){
var event = e || window.event;
if(event.target.innerHTML === 'Delete'){
var id = event.target.parentNode.parentNode.getElementsByTagName('td')[0].innerHTML;
var name = event.target.parentNode.previousSibling.getElementsByTagName('input')[0].value;
console.log(id,name);
var data = JSON.stringify({id:id,name:name});
deleteAjax('/products','DELETE',data);
}
})
}
// 分别加载每个事件,在页面完全载入后运行
loadEvent(showProd);
loadEvent(createProd);
loadEvent(updateProd);
loadEvent(deleteProd);
summary
通过对RESTful的实践加深了对expreess的学习以及理解,熟悉了通过ajax和后台数据的交互,代码中还有很多不合理的地方,希望大家多多指正
网友评论