js实现table表格动态更新数据并排序的思路
- 加载页面
即window.onload = function () {}。 - 获取服务器端缓存数据,初始化表格内容
第一步加载完成后,通过Ajax发起http请求,将服务器端的json数据转换成js对象,传回页面,填充表格table的初始内容,即各行id,name,num的值。 - 建立websocket连接,实现服务器端数据改变,前端页面实时更新表格内容
在websocket对象的onopen函数中利用定时器向服务器端每隔2秒发送1-50内的随机数,onmessage函数中,服务器端返回前端页面相同随机数数据。前端代码将服务器实时改变的随机数实现排序并填充表格table。num数值小的在上面,大的在下面。 - js实现表格排序
前端代码每次接收服务器端传过来的json数据ids,都将其转换成js对象ids,然后修改全局变量list.num的值。新建数组displayList,并将修改后的list内容填入数组,调用sort函数将list.num进行排序,再调用全局函数DisplayList填充表格table。
最终效果图
WebSocket服务器端代码(GO语言)
博文链接:https://blog.csdn.net/weixin_43757001/article/details/90116651
package main
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
"github.com/labstack/echo"
"github.com/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"`
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()