1.用的的技術
require.js 是用來模塊化開發,進行異步請求的 arttemplate.js 模板引擎是用來數據渲染的 jquery.js 是用來進行DOM操作和數據請求的 jquery.cookie.js 是用來儲存cookie的值得 bootstrap 它依賴有jquery,如果需要bootstrap.js前面需要引入jquery.js bootstrap.css 是用來進行樣式設置的 bootstrap.js 是用來動態交互的
2.login.html部分用到的技術
使用jquery的設置cookie的值 $.cookie("userInfo", JSON.stringify(res.result)); $.removeCookie("userInfo")刪除cookie值 需要下載jquery.cookie.js
頁面調轉 location.href = "/"; //location.href="index.html"
阻止默認行為 return false(jquery下才可以)
點擊獲取form的表單信息 觸發 submit 事件,在用serialize()獲取表單信息 $(this).serialize()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.css">
<link rel="stylesheet" href="css/login.css">
</head>
<body>
<div class="login-container">
<h3 class="text-center">博學谷后台管理系統</h3>
<form class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">用戶名</label>
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="" name="tc_name" value="前端學院">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">密碼</label>
<div class="col-sm-10">
<input type="password" class="form-control" placeholder="" name="tc_pass" value="123456">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success btn-block btn-lg">登錄</button>
</div>
</div>
</form>
</div>
</body>
<script src="js/lib/jquery-2.1.4.js"></script>
<script src="js/lib/jquery.cookie.js"></script>
<script>
$("form").on("submit", function () {
//1、獲取輸入的表單信息
var formData = $(this).serialize();
console.log(formData)
//2、提交到服務器
$.ajax({
type: "post",
url: "/api/login",
data: formData,
success: function (res) { //響應的:response
//為了實現login.html里面的數據可以再index.html里面進行訪問:
//a、h5本地存儲:localStorage/sessionStorage
//b、cookie:瀏覽器端的技術,也可以實現:在不跨域的前提下,任何頁面都可以訪問這些數據
console.log(res);
$.cookie("userInfo", JSON.stringify(res.result));
//c、session:服務器端的技術
var userInfoStr = $.cookie("userInfo");
console.log(userInfoStr); //JSON字符換
location.href = "/"; //location.href="index.html"
}
})
//出發點:減少服務器的壓力,將服務器驗證變成前端驗證
// -->前端驗證需要獲取數據,需要在用戶提交表單的時候,才能真正的獲取數據,而用戶用戶提交表單就會觸發form標簽的submit事件,
而submit事件的就會默認跳轉頁面(刷新頁面),而一旦跳轉頁面數據就丟失了,所以需要阻止該事件的默認行為
//阻止事件的默認行為-->同步提交表單
return false;
})
</script>
</html>
2. index.html 部分用到的技術點
使用bootstrap進行首頁布局 引入相應的css和js
引入require.js並與main.js建立聯系 data-main里面的“.js”可以省略
<script src="js/lib/require.js" data-main="main"></script>
給一個空盒子設置一個div來放切換的內容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.css">
<link rel="stylesheet" href="assets/datetimepicker/css/bootstrap-datetimepicker.css">
<link rel="stylesheet" href="assets/uploadify/uploadify.css"/>
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<!--側邊欄-->
<div class="aside">
<!--個人資料-->
<div class="profile-container">
<div class="img-container">
<img src="" class="img-circle img-responsive">
</div>
<h4 class="text-center"></h4>
</div>
<!--菜單欄-->
<div class="list-group">
<button type="button" class="list-group-item active btn-teacher">講師管理</button>
<button type="button" class="list-group-item btn-course">課程管理</button>
<button type="button" class="list-group-item btn-courseAdd">>>>創建課程</button>
<button type="button" class="list-group-item btn-course-message">>>>課程基本信息</button>
<button type="button" class="list-group-item btn-course-time">>>>編輯課時</button>
<button type="button" class="list-group-item btn-course-category">課程分類</button>
<button type="button" class="list-group-item btn-chart">圖表統計</button>
</div>
</div>
<!--右側內容區-->
<div class="content-container">
<!--頂部菜單欄-->
<div class="top panel panel-default">
<div class="panel-body">
<div class="row">
<div class="col-md-1">
<button type="button" class="btn btn-success" aria-label="Left Align">
<span class="glyphicon glyphicon-align-left" aria-hidden="true"></span>
</button>
</div>
<div class="col-md-1 col-md-offset-8">
<a href="#" class="personalCenter">個人中心</a>
</div>
<div class="col-md-1">
<a href="login.html" class="link-logout">退出</a>
</div>
</div>
</div>
</div>
<!--要切換內容的區域-->
<div class="menu-content-container">
</div>
</div>
</body>
<script src="js/lib/require.js" data-main="main"></script>
</html>
3. main.js 部分用到的技術點,它就是個主模塊,是個大心臟,子模塊都會引入到這里
require的配置問題 使用require.config({})來進行配置
baseUrl 鍵值對 來設置默認路徑 baseUrl:"js"
paths 鍵值對對象 來設置路徑 paths:{jquery:"lib/jquery-2.1.4",cookie:"lib/jquery.cookie"}
shim 鍵值對對象來 來設置模塊依賴 shim:{bootstrap:{deps:["jquery"] }}
require(["a.js","b.js"],function(a,b){...})
當他觸發默認事件的時候觸發a.js也就是 $(this).a("我是石順麟") 會跟a.js建立聯系並把"我是石順麟"通過形參傳過去了
a.js 子模塊需要設置按需加載的問題 並用define(["c.js","d.js"],function(){ return function(name){處理業務邏輯name="我是石順麟"} })
設置ajax的全局默認樣式 jquery的方法 $.ajaxSetup(beforeSend:function(){發送ajax等待的業務邏輯},complete:function(){數據請求回來之后的業務邏輯})
把JSON字符換轉化成JSON對象 JSON.parse(userInfoStr)
實現菜單欄切換功能 通過事件委托為按鈕注冊事件判斷該類名是哪個 用HTML5的 hasclass("demo")方法
自動觸發事件 $(".aside .list-group button.btn-teacher").trigger("click"); trigger()方法
退出功能 刪除cookie值 $.removeCookie("userInfo") 並調轉到登錄頁面 location.href="login.html"
/**
* 這是注釋的內容
* Author:Wilbert
*/
require.config({
baseUrl:"js",//設置默認路徑
paths:{ //設置路徑
jquery:"lib/jquery-2.1.4",
cookie:"lib/jquery.cookie",
text:"lib/text",
arttemplate:"lib/template-web",
//配置tpls文件夾路徑
tpls:"../tpls",
bootstrap:"../assets/bootstrap/js/bootstrap",
datatime:"../assets/datetimepicker/js/bootstrap-datetimepicker",
//上傳控件
upload:"../assets/uploadify/jquery.uploadify",
//配置ueditor
ueConf:"../assets/ueditor/ueditor.config",
ueAll:"../assets/ueditor/ueditor.all",
ZeroClipboard:"../assets/ueditor/third-party/zeroclipboard/ZeroClipboard",
//配置百度圖表控件
echarts:"lib/echarts.min"
},
shim:{ //設置依賴模塊
bootstrap:{
deps:["jquery"] //依賴jQuery
},
datatime:{
deps:["bootstrap"] //依賴bootstrap
},
upload:{
deps:["jquery"]
}
}
})
require(["jquery","teacher/list","courseCategory/list","course/list","course/add","course/editMessage","couserTime/list","course/personalCenter","text!tpls/loading.html","char","cookie"],
function($,teacherList,courseCategory,courseList,courseAdd,editMessage,coursetime,personalCenter,loadingTpl,chart){
var $modalloading = $(loadingTpl)
//設置ajax請求的全局默認樣式,所有的ajax請求都可以用的
$.ajaxSetup( {
beforeSend:function(){
//console.log("發送ajax之前");
//再每次發送ajax之前把前面的模態框刪除掉
//$("#modalloading").remove();
$modalloading.appendTo("body").modal();
},
complete:function(){
$modalloading.on("hidden.bs.modal",function(){
$modalloading.remove();
}).modal("hide");
}
})
//1在cookie中獲取保存的數據
var userInfoStr=$.cookie("userInfo");
//console.log(userInfoStr); //JSON字符換
//如果獲取不到cookie,說明沒有登錄過,跳轉到登錄頁面
if(!userInfoStr){
location.href="login.html";
}
var userInfo=JSON.parse(userInfoStr); //把JSON字符換轉化成JSON對象
//console.log(userInfo);
//2、更新用戶名和頭像
$(".profile-container .img-container img").attr("src",userInfo.tc_avatar);
$(".profile-container h4").text(userInfo.tc_name);
//3、實現菜單欄切換
$(".aside .list-group").on("click","button",function(){
//實現菜單背景的切換
$(this).addClass("active").siblings().removeClass("active");
//a、講師管理
if($(this).hasClass("btn-teacher")){
teacherList();
}else if($(this).hasClass("btn-course")){
//b、課程管理
courseList();
}else if($(this).hasClass("btn-course-category")){
//b、課程分類
courseCategory();
}else if($(this).hasClass("btn-chart")){
//alert("圖表統計模塊")
//b、圖表統計
chart();
}else if($(this).hasClass("btn-courseAdd")){
//b、創建課程
courseAdd();
}else if($(this).hasClass("btn-course-message")){
//b、課程基本信息
editMessage();
}else if($(this).hasClass("btn-course-time")){
//b、課時管理
coursetime();
}
});
//5.觸發個人中心事件
$(".panel-body .personalCenter").on("click",function(){
personalCenter();
})
//6.為退出注冊事件
$(".link-logout").on("click",function(){
//發送ajax請求 使其到登錄狀態
$.post("api/logout",{},function(){
//刪除cookie的值
$.removeCookie("userInfo")
console.log($.cookie("userInfo"));
//調轉到登錄界面
//location.href="login.html";
})
})
//4、自動觸發講師管理按鈕的點擊事件
$(".aside .list-group button.btn-teacher").trigger("click");
})
4.講師管理模塊 teacher/list.js,所用到的技術
text.js 用於異步加載文本資源如txt、css、html、xml、svg等。
首先需要在主模塊中配置text.js,其次在相應模塊引入html文件
發送get請求 $.get("api",{},function(res){這里處理業務邏輯})
發送post請求 $.post("api",{},function(res){處理業務邏輯})
報錯功能 throw new Error("數據請求錯誤")
調用arttemplate的render()方法 art.render("html字符串",res返回來的數據)
把字符串html追加到一個盒子當中使用append()方法前提是使用empty()來清空盒子內容,$("#id").empty().append($teacherList)
鏈式編程直接在后面 "."就可以了
啟用和注銷按鈕模塊沒有html渲染直接放在了講師管理模塊
點擊注銷按鈕獲取相應的ID值並發送ajax請求,獲取更新后的狀態值再來改變注銷按鈕的的值用text("")方法
/**
* 講師主模塊-->講師列表
* Author:Wilbert
*/
define(["jquery", "text!tpls/teacherList.html", "arttemplate", "teacher/showInfo","teacher/add","teacher/edit"], function ($, teacherListTpl, art, teacherShowInfo,teacherAdd,teacherEdit) {
//art接受了arttemplate模板引擎的返回值-->全局函數:template
return function () {
//3個參數:url/參數/success方法的回調函數
$.get("/api/teacher", {}, function (res) {
//優化前:
// if(res.code==200){
// //數據正常返回-->數據加載到表格中
// }else {
// //數據發生了異常
// throw new Error(res.msg);
// }
//優化后:
if (res.code != 200) throw new Error(res.msg);
console.log(res);
//----->代碼能夠執行到這里,數據一定成功返回
var teacherList = art.render(teacherListTpl, res); //teacherList:"<div></div>"
//console.log(teacherList);
var $teacherList = $(teacherList);
//console.log($teacherList);
$teacherList
//調用講師增加模塊
.on("click",".btn-add-teacher",function(){
teacherAdd();
})
//啟動注銷模塊
.on("click", ".btn-status", function () {
//實現修改用戶狀態
//a、修改頁面中相應的文本
//b、修改服務器中保存的數據
//實現思路:b-->a
var $btn = $(this);
var data = {
tc_id: $(this).parent().attr("tc_id"),
tc_status: $(this).parent().attr("tc_status")
};
$.post("/api/teacher/handle", data, function (res) {
if (res.code != 200) throw new Error(res.msg);
//獲取到更新后的狀態值
var tc_status = res.result.tc_status;
//修改頁面中的文本
//1、修改按鈕的文本 //0表示啟用狀態
$btn.text(tc_status == 0 ? "注銷" : "啟用");
//2、修改屬性
$btn.parent().attr("tc_status", tc_status);
//3、修改指定"用戶狀態列"的文本
$btn.parent().siblings(".td-status").text(tc_status == 0 ? "啟用" : "注銷");
})
})
.on("click", ".btn-show", function () {
var tc_id = $(this).parent().attr("tc_id");
//實現查看講師信息
teacherShowInfo(tc_id);
})
//調用編輯講師模塊
.on("click",".btn-edit",function(){
var tc_id = $(this).parent().attr("tc_id")
// console.log(tc_id);
teacherEdit(tc_id);
});
//$("<div></div>").appendTo("body"); //-->將字符串轉換為dom元素,把該dom元素放到body中
//$(".menu-content-container").html(teacherList);//又會將字符串轉換為另一個dom元素,將dom元素放到頁面中
$(".menu-content-container").empty().append($teacherList);
})
};
});
5.添加講師模塊 teacher/add.js 所用到的技術點
使用了bootstrap的model()方法事件觸發模塊框會置頂,前提是先清空以前的模塊框用remove()方法,不然會創建無數個模塊框
使用 submit事件 用jquery的serialize()方法獲取獲取表單信息對象,前提是表單需要有name屬性
使用日期控件,首先給盒子加個類名比如data-join ,其次用find(".data-join").datetimepicker({})來初始化日期控件
/**
* 增加講師模塊
*/
define(["jquery", "text!tpls/teacherAdd.html", "bootstrap","datatime"], function ($, teacherAddTpl) {
return function () {
$("#modalAddTeacher").remove();
// console.log(teacherAddTpl);
var $teacherAdd = $(teacherAddTpl)
.on("submit", "form", function () {
var FormData = $(this).serialize();
// console.log(FormData);
//組織默認提交按鈕刷新真個頁面
// $('#modalAddTeacher').modal('hide')
// console.log(FormData);
$.post("api//teacher/add", FormData, function (res) {
// console.log(res);
// 沒有發送成功就報錯
if (res.code !== 200) throw new Error(res.msg);
//讓模態框隱藏
$teacherAdd.modal("hide");
//到了這步說明提交數據成功 刷新講師模塊
$(".aside .list-group button.btn-teacher").trigger("click");
})
return false;
})
.appendTo("body").modal()
//初始化日期控件
$teacherAdd.find(".date-join").datetimepicker({
format: 'yyyy-mm-dd', //格式化日期格式
language:"zh-CN", //選擇語言,需要引入語言包
daysOfWeekDisabled:[1,2], //指定周幾不能用
autoclose:true, //選完一個日期之后就會自動隱藏日期框
minView:"month",
todayBtn:true,
todayHighlight:true //當選擇其他日期的時候,高亮今天的日期
});
}
});
6. 講師查看模塊 teacher/showInfo.js,用到的技術
首先用形參tc_id來接口講師列表模塊傳過來的ID值
其次用這個id發送ajax請求,來獲取相應的信息
再用arttemplete模板引擎的render方法把數據放在html頁面中
/**
* 查看講師信息
* Author:Wilbert
*/
define(["jquery","text!tpls/teacherShowInfo.html","arttemplate","bootstrap"],function ($,teacherShowInfoTpl,art) {
return function (tc_id) {
//獲取指定講師的信息
$.get("/api/teacher/view",{tc_id:tc_id},function(res){
if(res.code!=200) throw new Error(res.msg);
$("#modalTeacherInfo").remove();
var teacherShowInfo=art.render(teacherShowInfoTpl,res.result);
$(teacherShowInfo).appendTo("body").modal();
});
};
});
7.講師編輯模塊 teacher/edit.js,用到的技術
使用形參來接收講師列表模塊list.js傳過來的ID值,
通過ID值來發送ajax請求來獲取對應的信息
通過arttemplate.render("模板字符串",res)方法吧獲取的數據仿造模板字符串中
通過submit事件用jquery的 serialize()方法來獲取表單信息並發送ajax請求,請求成功后用隱藏模塊框刷新講師管理模塊功能
使用jquery的appendTo("body")把代碼字符串放到body中並追加bootstrap的model()方法來增加模塊框方法
/**
* 講師編輯模塊
*/
define(["jquery", "text!tpls/teacherEdit.html","arttemplate", "bootstrap", "datatime"], function ($, teacherEditTpl,art) {
return function (tc_id) {
console.log("講師編輯模塊")
$.get("api//teacher/edit",{tc_id:tc_id},function(res){
if(res.code != 200) throw new Error(res.msg);
// console.log(res);
//刪除以前的
$("#modalEditTeacher").remove();
var teacherEdit = art.render(teacherEditTpl,res.result)
//點擊編輯模態框保存數據並發送請求刷新頁面
var $teacherEdit = $(teacherEdit)
.on("submit","form",function(){
var FormData = $(this).serialize();
console.log(FormData);
//得到form表單的數據 但是沒有tc_id用hidden隱藏域把它加上去
//把得到的數據發放修改講師 發送post請求
$.post("api//teacher/update",FormData,function(res){
console.log(res);
// 判斷有沒有發送請求成功
if(res.code !=200) throw new Error(res.msg);
//防模態框隱藏 調用 modal("hide")方法會隱藏
$teacherEdit.modal("hide");
//刷新講師管理頁面 調用它的單機事件 trigger("click")
$(".aside .list-group button.btn-teacher").trigger("click");
})
//異步請求防止刷新頁面
return false;
})
.appendTo("body").modal();
})
//初始化日期控件
// $teacherEdit.find(".date-join").datetimepicker({
// format: 'yyyy-mm-dd', //格式化日期格式
// language: "zh-CN", //選擇語言,需要引入語言包
// daysOfWeekDisabled: [1, 2], //指定周幾不能用
// autoclose: true, //選完一個日期之后就會自動隱藏日期框
// minView: "month",
// todayBtn: true,
// todayHighlight: true //當選擇其他日期的時候,高亮今天的日期
// });
}
})
8.上傳控件的使用
1.首先定義一個file標簽 <input type="file" id="picUpload">
<div class="panel panel-default">
<div class="panel-body">
<ol class="breadcrumb">
<li><a href="#">課程管理</a></li>
<li class="active">課程圖片</li>
</ol>
<div class="media">
<div class="media-left">
<a href="javascript:void(0)">
{{if(!cs_cover)}}
<img class="media-object" src="imgs/course.png" alt="" width="240" height="120">
{{else}}
<img class="media-object" src="{{cs_cover}}" alt="" width="240" height="120">
{{/if}}
</a>
</div>
<div class="media-body">
<h4>課程名稱:{{cs_name}}</h4>
<h4 class="media-heading">講師名稱:{{tc_name}}</h4>
<input type="file" id="picUpload">
</div>
</div>
</div>
</div>
2.初始化上傳控件的使用
/**
* 圖片修改模塊
* Created by Administrator on 2017/7/6.
*/
define(["jquery","text!tpls/coursePic.html","arttemplate","bootstrap","upload"],function($,coursePicTpl,art){
return function(cs_id){
$.get("api/course/picture",{cs_id:cs_id},function(res){
//console.log(res);
var coursePic = art.render(coursePicTpl,res.result);
var $coursePic = $(coursePic);
$(".menu-content-container").html($coursePic);
//初始化上傳插件
$("#picUpload").uploadify({
fileObjName: "cs_cover_original", //提交到服務器的name值
formData: {cs_id: cs_id}, //需要提交到服務器的額外的數據
height: 30,
swf: '../../assets/uploadify/uploadify.swf', //必填、放一個swf文件
uploader: '/api/uploader/cover', //請求的地址
width: 120,
itemTemplate: "<span></span>", //指定上傳的內容模板
//文件上傳成功之后執行的函數
onUploadSuccess: function (file, data, response) {
// alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ':' + data);
//跳轉到課程列表界面
$(".btn-course").trigger("click");
}
});
})
}
})
9.圖表統計模塊 char.js 和char.html,用到的技術點
1.在html中設置寬高和類名
<div class="chart" style="width:600px;height:400px;border:1px solid red;"></div>
2.基於准備好的dom,初始化echarts實例
var myChart = echarts.init($chart.find(".chart").get(0));
3.復制scharts提供的代碼
var option={}
4.基於上面的myChart實例來指定的配置項和數據顯示圖表
myChart.setOption(option);
/**
* 圖表統計模塊 js部分
* Created by Administrator on 2017/7/7.
*/
define(["jquery", "text!tpls/chart.html", "echarts"], function ($, chartTpl, echarts) {
return function () {
//得到chart.html字符串並轉化為jQuery對象並把它放到HTML上
var $chart = $(chartTpl);
$(".menu-content-container").html($chart);
// 基於准備好的dom,初始化echarts實例
var myChart = echarts.init($chart.find(".chart").get(0));
//發送ajax請求得到男女人數和比例
$.get("api/teacher", {}, function (res) {
//用得到的數據統計男女人數
var date = res.result;
//新建一個空對象 統計男女人數
var genderArray = [{
name: "男",
value: 0
},
{
name: "女",
value: 0
}
];
date.forEach(function (v) {
if (v.tc_gender == "0") {
genderArray[0].value++;
} else {
genderArray[1].value++;
}
})
var option = {
//標題
title: {
text: "講師中男女比例",
subtext: "副標題"
},
//懸浮框
tooltip: {
trigger: 'item',
//指定了懸浮框的內容
formatter: "{a} <br/>{b}: {c} ({d}%)"
},
//圖例
legend: {
//show:false, //圖例是否可見
//指定對齊方式
orient: 'horizontal',
// x: 'left',
right: 50, //右對齊
data: ["男", "女"],
textStyle: {
// fontFamily:"宋體",
// fontSize:30
}
},
//數據
series: [{
name: '訪問來源',
type: 'pie', //type指定了圖形的類型-->pie:餅圖
radius: ['50%', '70%'], //分別制定了內外圓的半徑
avoidLabelOverlap: false,
label: {
normal: {
show: false,
position: 'center'
},
emphasis: {
show: true,
textStyle: {
fontSize: '30',
fontWeight: 'bold'
}
}
},
labelLine: {
normal: {
show: false
}
},
//數據
data: genderArray
}]
};
// 使用剛指定的配置項和數據顯示圖表。
myChart.setOption(option);
})
}
})
//圖表控件HTML部分
<div class="panel panel-default"> <div class="panel-body"> <ol class="breadcrumb"> <li><a href="#">圖表統計</a></li> <li class="active">餅圖</li> </ol> <div class="chart" style="width:600px;height:400px;border:1px solid red;"></div> </div> </div>
