js实现table表格动态更新数据并排序
js实现table表格动态更新数据并排序的思路
1. 加载页⾯
即load = function () {}。
2. 获取服务器端缓存数据,初始化表格内容
第⼀步加载完成后,通过Ajax发起http请求,将服务器端的json数据转换成js对象,传回页⾯,填充表格table的初始内容,即各⾏id,name,num的值。
3. 建⽴websocket连接,实现服务器端数据改变,前端页⾯实时更新表格内容
在websocket对象的onopen函数中利⽤定时器向服务器端每隔2秒发送1-50内的随机数,onmessage函数中,服务器端返回前端页⾯相同随机数数据。前端代码将服务器实时改变的随机数实现排序并填充表格table。num数值⼩的在上⾯,⼤的在下⾯。
4. js实现表格排序
前端代码每次接收服务器端传过来的json数据ids,都将其转换成js对象ids,然后修改全局变量list.num的值。新建数组
sort函数 js
displayList,并将修改后的list内容填⼊数组,调⽤sort函数将list.num进⾏排序,再调⽤全局函数DisplayList填充表格table。
最终效果图
WebSocket服务器端代码(GO语⾔)
package main
import(
"fmt"
"net/http"
"github/gorilla/websocket"
"github/labstack/echo"
"github/labstack/echo/middleware"
)
var(
upgrader = websocket.Upgrader{}
)
func main(){
e := echo.New()
// e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Static("/","./")
e.GET("/hello",func(c echo.Context)error{
return c.String(http.StatusOK,"Hello, World!")
})
e.GET("/echo", getEcho)
e.POST("/echo", postEcho)
e.GET("/list",func(c echo.Context)error{
type Camera struct{
ID  string`json:"id"`
Name string`json:"name"`
Name string`json:"name"`
Num  int`json:"num"`
}
type List struct{
List []Camera `json:"list"`
}
list :=new(List)
c1 := Camera{"001","camera1",10}
c2 := Camera{"002","camera2",20}
c3 := Camera{"003","camera3",30}
list.List =append(list.List, c1)
list.List =append(list.List, c2)
list.List =append(list.List, c3)
return c.JSON(http.StatusCreated, list)
})
e.GET("/ws", wsEcho)
e.Logger.Fatal(e.Start(":8800"))
}
func wsEcho(c echo.Context)error{
ws, err := upgrader.Upgrade(c.Response(), c.Request(),nil)
if err !=nil{
return err
}
defer ws.Close()
// Write
err = ws.WriteMessage(websocket.TextMessage,[]byte("Hello, Client!")) if err !=nil{
c.Logger().Error(err)
}
for{
// Read
_, msg, err := ws.ReadMessage()
if err !=nil{
c.Logger().Error(err)
}
fmt.Printf("wsEcho:%s\n", msg)
// Write
err = ws.WriteMessage(websocket.TextMessage,[]byte(msg))
if err !=nil{
c.Logger().Error(err)
}
}
}
// get url /echo?str="xxxxx"
func getEcho(c echo.Context)error{
str := c.QueryParam("str")
return c.String(http.StatusOK, str)
}
// post url /echo with body form value "str"
func postEcho(c echo.Context)error{
str := c.FormValue("str")
return c.String(http.StatusOK, str)
}
由以上可以看出,服务器端储存着json数据
{
"list":[ {"id":"001","name":"camera1","num":10}, {"id":"002","name":"camera2","num":20}, {"id":"003","name":"camera3","num":30}
]
}
html代码
<body>
<div>
<table id="customers">
<tr id="one">
<th>id</th>
<th>name</th>
<th>num</th>
</tr>
<tr>
<td></td>
<!--id_one-->
<td></td>
<!--name_one-->
<td></td>
<!--num_one-->
</tr>
<tr class="alt">
<td></td>
<!--id_two-->
<td></td>
<!--name_two-->
<td></td>
<!--num_two-->
</tr>
<tr>
<td></td>
<!--id_three-->
<td></td>
<!--name_three-->
<td></td>
<!--num_three-->
</tr>
</table>
</div>
</body>
css代码
<style type="text/css">
#customers{
font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
width: 100%;
border-collapse: collapse;
}
#customers td,
#customers th{
font-size: 1em;
border: 1px solid #98bf21;
padding: 3px 7px 2px 7px;
}
#customers th{
font-size: 1.1em;
text-align: left;
padding-top: 5px;
padding-bottom: 4px;
background-color: #A7C942;
color: #ffffff;
}
#customers tr.alt td{
color: #000000;
background-color: #EAF2D3;
}
</style>
js代码
<script type="text/javascript">
var list ={};//list对象储存各⾏id,name,num的值
//遍历displayList数组,将数组中的数据传回页⾯,填充table表格各⾏id,name,num的值function DisplayList(displayList){
var customers = ElementById("customers");
displayList.forEach(function(obj, i){
})
}
//Ajax获取后台id,name,num的值
var xmlhttp;
if(window.XMLHttpRequest){
//  IE7+, Firefox, Chrome, Opera, Safari 浏览器执⾏代码
xmlhttp =new XMLHttpRequest();
console.log(xmlhttp);
}
else{
// IE6, IE5 浏览器执⾏代码
xmlhttp =new ActiveXObject("Microsoft.XMLHTTP");
}
console.log('xmlreadyState:'+ adyState);
console.log('xmlstatus:'+ xmlhttp.status);
adyState ==4&& xmlhttp.status ==201){
//初始化table内容
//将服务器端json数据转成js对象,传回前端页⾯
var json = sponseText;
var json = sponseText;
console.log(json);
var jsonToJs =JSON.parse(json);
console.log(jsonToJs);
//填充list对象的内容,准备初始化table内容,注意此处list对象的索引为jsonToJs.list[i]的id值,⽽⾮常规的从0开始的索引号for(var i =0; i < jsonToJs.list.length; i++){
list[jsonToJs.list[i].id]= jsonToJs.list[i];
console.log(jsonToJs.list[i]);
}
console.log(list);
DisplayList(jsonToJs.list);//初始化table内容
//建⽴websocket连接
var ws =new WebSocket("ws://127.0.0.1:8800/ws");
var interval_num;
function sortDisplayList(a, b){
return a.num - b.num;
}
console.log("open");
function rnd(n, m){
var random = Math.floor(Math.random()*(m - n +1)+ n);
return random;
}
interval_num =setInterval(function(){
var ids ={};
ids["001"]=rnd(1,50);
ws.send(JSON.stringify(ids));
},2000);
};
if(evt.data.indexOf("Hello")!=-1){
return;
}
var ids =JSON.parse(evt.data);
list["001"].num = ids["001"];
var displayList =new Array();
for(id in list){
displayList.push(list[id]);
}
displayList.sort(sortDisplayList);
DisplayList(displayList);
};
console.log("WebSocketClosed!");
};
console.log("WebSocketError!");
};
}
}
xmlhttp.open("GET","127.0.0.1:8800/list",true);
xmlhttp.send();
}
</script>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。