提问人:code_freshgirl 提问时间:7/5/2023 最后编辑:code_freshgirl 更新时间:7/5/2023 访问量:32
ajax.reload() 表,但希望保留表的同一页而不是回到第一页
ajax.reload() table but want to keep the same page of the table instead of back to first
问:
我有两个表格“表格”和“status_table”,每 3 秒设置一次会刷新显示器,但是当我转到表格的第二页时,3 秒后会翻回第 1 页,我想刷新表格,但也要保留我所在的页面,(在表格中)
我的两张桌子截图(“桌子”是那6块,而“status_table”可以翻页)
- 这是核心功能
setInterval(function() {
$('table').DataTable().ajax.reload();
$('status_table').DataTable().ajax.reload();
}, 3000);
这是表格 datatables.net 演示的模板
- 如果需要,这是代码的完整版本
<!DOCTYPE html>
<html lang="en">
<head>
<title>Main</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap 4.2.1 CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>
</main>
<div class="m-4">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<div class="d-flex align-items-center">
<a href="#" class="navbar-brand">
<img src="assets\img\我的项目.png" height="40" alt="gyro-pic">
</a>
<button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target="#navbarCollapse">
<span class="navbar-toggler-icon"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="navbarCollapse">
<div class="navbar-nav">
<a href="Main.html" class="nav-item nav-link active" style="font-family: Arial Black;">Main</a>
<a href="IPC.html" class="nav-item nav-link" ;>E84 IPC Management</a>
<a href="ServerManage.html" class="nav-item nav-link">Server Management</a>
<a href="Log.html" class="nav-item nav-link" >Log Management</a>
<a href="Alarm.html" class="nav-item nav-link">Alarm Management</a>
<a href="AcctManage.html" class="nav-item nav-link">Account Management</a>
</div>
<div class="navbar-nav ml-auto" style="margin-top: 20px;" >
<ul style="list-style-type: none">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<img src="assets\img\user_icon.png" height="36" alt="gyro-pic">
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownMenuLink">
<span style="font-family: serif; color: rgb(0, 123, 255); padding-left: 24px; font-size: 18px;">User:</span>
<span id="result_userid"
style="font-family: serif; color: rgb(0, 123, 255); font-size: 18px;"></span><br>
<script>
document.getElementById("result_userid").innerHTML = localStorage.getItem("userid");
</script>
<span style="font-family: serif; color: rgb(0, 123, 255); padding-left: 24px; font-size: 18px;">Name:</span>
<span id="result_name"
style="font-family: serif; color: rgb(0, 123, 255); font-size: 18px;"></span>
<script>
document.getElementById("result_name").innerHTML = localStorage.getItem("name");
</script>
<a class="dropdown-item" href="index.html"
style="font-size: 16px;">Login page</a>
<a id="logout-link" class="dropdown-item" href="logout.html"
style="font-size: 16px;">Logout</a>
</div>
</li>
</ul>
</div>
</div>
</div>
</nav>
</div>
<script>
document.getElementById("logout-link").addEventListener("click", function() {
localStorage.removeItem("token");
});
setInterval(function() {
$('table').DataTable().ajax.reload();
$('status_table').DataTable().ajax.reload();
}, 3000);
</script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"
></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.4.0/axios.min.js" integrity="sha512-uMtXmF28A2Ab/JJO2t/vYhlaa/3ahUOgj1Zf27M5rOo8/+fcTUVH0/E0ll68njmjrLqOBjXM3V9NiPFL5ywWPQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<!-- <script defer src="login-page.js"></script> -->
<style>
.custom-bg-orange {
background-color: rgb(255, 119, 0);
}
.dataTables_wrapper {
margin-left: 20px;
margin-right: 30px;
}
.btn-reset {
margin-right: 10px;
margin-bottom: 10px;
width: 80px;
height: 40px;
}
</style>
<div id="status_table" class="m-4" style="width: 1060px; margin-left: 40px; margin-right: 20px;">
<div class="row">
<div class="col custom-bg-orange m-3 p-3 rounded" style="color: #F0F0F0;">
ALARM: <span id="alarm_dta">0</span>
</div>
<div class="col bg-danger m-3 p-3 rounded" style="color: #F0F0F0;">
ERROR: <span id="error_dta">0</span>
</div>
<div class="col bg-warning m-3 p-3 rounded" style="color: #F0F0F0;">
OFFLINE: <span id="offline_dta">0</span>
</div>
<div class="col bg-secondary m-3 p-3 rounded" style="color: #F0F0F0;">
DISABLE: <span id="disable_dta">0</span>
</div>
<div class="col bg-primary m-3 p-3 rounded" style="color: #F0F0F0;">
NORMAL: <span id="normal_dta">0</span>
</div>
<div class="col bg-success m-3 p-3 rounded" style="color: #F0F0F0;">
TOTAL: <span id="total_dta">0</span>
</div>
</div>
</div>
<script>$(document).ready(function() {
const getToken = localStorage.getItem("token");
console.log("getToken01:", getToken);
var statusCounts_02; // 宣告 statusCounts_02 變數
function refreshStatusTable() {
$.ajax({
url: "http://192.168.01.10:3000/api/item/status",
headers: {
'Authorization': 'Bearer ' + getToken
},
success: function(response) {
var data = response.ipc_status;
var statusCounts = {};
var disableCount = 0; // 计算"ipc_enable"为false的数量
for (var i = 0; i < data.length; i++) {
var status = data[i].status;
if (statusCounts[status]) {
statusCounts[status]++;
} else {
statusCounts[status] = 1;
}
if (!data[i].ipc_enable) {
disableCount++;
}
}
console.log("Status Counts-02:", statusCounts);
statusCounts_02 = Object.assign({}, statusCounts);
// 更新 ALARM 的數字
document.getElementById("alarm_dta").innerText = statusCounts_02["Alarm"] || "0"; // 要注意
// 更新 ERROR 的數字
document.getElementById("error_dta").innerText = statusCounts_02["Error"] || "0";
// 更新 OFFLINE 的數字
document.getElementById("offline_dta").innerText = statusCounts_02["Offline"] || "0";
// 更新 DISABLE 的數字
document.getElementById("disable_dta").innerText = disableCount.toString();
// 更新 NORMAL 的數字
document.getElementById("normal_dta").innerText = statusCounts_02["Normal"] || "0";
// 更新 TOTAL 的數字
var totalCount = 0;
for (var key in statusCounts_02) {
totalCount += parseInt(statusCounts_02[key]);
}
document.getElementById("total_dta").innerText = totalCount.toString();
}
});
}
refreshStatusTable(); // 初始加载一次数据
setInterval(refreshStatusTable, 3000); // 每3秒刷新数据
});
</script>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"
></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.4.0/axios.min.js" integrity="sha512-uMtXmF28A2Ab/JJO2t/vYhlaa/3ahUOgj1Zf27M5rOo8/+fcTUVH0/E0ll68njmjrLqOBjXM3V9NiPFL5ywWPQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id="app"></div>
<table id="example" class="display"></table>
<!-- JavaScript libraries -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
var Selected_add_edit_api; // 全域變數,儲存點擊按鈕所在列的資料
$(document).ready(function () {
const getToken = localStorage.getItem("token")
console.log("GET TOKEN", getToken)
var table = $("#example").DataTable({
ajax: {
url: "http://192.168.01.10:3000/api/item/status",
headers: {
'Authorization': 'Bearer ' + getToken
},
dataSrc: function (response) {
console.log("DATA", response);
return response.ipc_status
}
},
columns: [
{
data: null,
title: "ACTION",
render: function (data, type, row) {
return '<button class="btn btn-success delete-btn btn-reset" id="Delete_Data" data-id="' + row.device_id + '">Reset</button>';
}
},
{ data: "device_id", title: "device_id" },
{ data: "name", title: "name" },
{ data: "group", title: "group" },
{ data: "ip", title: "ip" },
{ data: "port", title: "port" },
{ data: "ipc_enable", title: "ipc_enable" },
{ data: "ftp_enable", title: "ftp_enable" },
{ data: "status", title: "status" },
{ data: "detail", title: "detail" }
]
});
table.draw()
// Edit row function
var rowData; // 全域變數,儲存點擊按鈕所在列的資料
var Reset_API_data; // 全域變數,儲存點擊按鈕所在列的資料
$('#example tbody').on('click', 'button', function (event) {
var data = table.row($(this).parents('tr')).data();
rowData = data;
console.log("GET select DATA", data)
const { device_id, port: port_id } = data;
Reset_API_data = { device_id, port_id };
console.log("Data for Reset API", Reset_API_data)
});
$(function() {
$('#exampleModal').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget);
var recipient = button.data('whatever');
var modal = $(this);
var data = rowData;
var inputFields = modal.find('.modal-body input');
if (button.attr('id') == "AddedNew_Data02" || button.attr('id') == "AddedNew_Data" ) { ///// 從這不一樣的,可以從這插入
inputFields.val("");
modal.find('.modal-title').text('Add Data ' + recipient);
Selected_add_edit_api = "add-api"; //// 我試試拿這個當save() 判斷式
} else {
var keys = Object.keys(data);
for (var i = 0; i < inputFields.length; i++) {
var inputValue = data[keys[i]];
var inputValue = rowData[keys[i]];
modal.find('.modal-title').text('Reset' + recipient);
Selected_add_edit_api = "edit-api"; //// 我試試拿這個當save() 判斷式
$(inputFields[i]).val(inputValue);
}
}
});
});
function editRow_website(id){
var device_id=document.getElementById("device_id"+id);
var name=document.getElementById("name"+id);
var group=document.getElementById("group"+id);
var ip=document.getElementById("ip"+id);
var port=document.getElementById("port"+id);
var ipc_enable=document.getElementById("ipc_enable"+id);
var ftp_enable=document.getElementById("ftp_enable"+id);
var status=document.getElementById("status"+id);
var detail=document.getElementById("detail"+id);
let getEditData = {
"device_id": device_id,
"email_data": name,
"address_data": group,
"name_data": ip,
"email_data": port,
"address_data": ipc_enable,
"name_data": ftp_enable,
"status":status,
"detail":detail,
}
document.getElementById("#editid input").value = device_id
}
$(document).on('click', '.delete-btn', function (event) { // 是叫delete 但 work Reset
var id = $(this).data('id')
console.log("GET Reset ID", id)
confirmReset(id)
});
function deleteData(id) {
$.ajax({
url: "http://192.168.01.10:3000/api/item/status/?device_id="+ id,
type:'DELETE',
headers: {
'Authorization': 'Bearer ' + getToken // 只要call api 要加header 的授權
},
success: function(response){
console.log(response);
}
}).then(res => console.log("RES", res));
}
function resetData(data) {
var postData_demo = 'device_id=test--093&port_id=0'
var postData = '';
for (var key in Reset_API_data) {
if (postData !== '') {
postData += '&';
}
postData += key + '=' + Reset_API_data[key];
}
$.ajax({
url: `http://192.168.01.10:3000/api/item/status/resetport?${postData}`, /// api change ///
type:'GET', // get for reset
dataType : 'json',
contentType : 'application/json; charset=UTF-8', // 不能用 'application/json; charset=utf-8'
data :JSON.stringify(data) , // 不用JSON.stringify()
headers: {
'Authorization': 'Bearer ' + getToken // 只要call api 要加header 的授權
},
success: function(response){
console.log("SUCCESS",response);
},
error: function(response){
console.log("ERROR",response);
}
})
}
function confirmDelete(id) {
if (confirm("確定要delete 此 嗎?")== true) {
var table = $("#example").DataTable();
var row = table.row($(this).closest('tr'));
deleteData(id);
if (row.length > 0) {
row.remove().draw();
console.log("Delete row with id:", id);
}
} else{
none
}
}
function confirmReset(Reset_API_data) {
if (confirm("確定要Reset 此 IPC 嗎?")== true) {
var table = $("#example").DataTable();
var row = table.row($(this).closest('tr'));
resetData(Reset_API_data);
if (row.length > 0) {
row.remove().draw();
console.log("Reset this IPC with id:", id);
}
} else{
none
}
}
});
</script>
<script src="script.js"></script>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">device_id:</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="input_edit_device_id" class="col-form-label">Device ID:</label>
<input type="text" class="form-control" id="input_edit_device_id">
</div>
<div class="form-group">
<label for="input_edit_name" class="col-form-label">Port:</label>
<input type="text" class="form-control" id="input_edit_name">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="save()">Submit</button>
</div>
</div>
</div>
</div>
<script>
function AddRow(data) {
const getToken = localStorage.getItem("token")
console.log(data)
// 清空輸入框的值
$("#input_edit_device_id").val("");
$("#input_edit_name").val("");
$("#input_edit_data_group").val("");
$("#input_edit_data_ip").val("");
$("#input_edit_data_port").val("");
$("#input_edit_data_ipc_enable").val("");
$("#input_edit_data_status").val("");
$("#input_edit_data_detail").val("");
$.ajax({
url: 'http://192.168.01.10:3000/api/item/status',
type:'POST', // add
dataType : 'json',
contentType : 'application/json; charset=UTF-8', // 不能用 'application/json; charset=utf-8'
data :JSON.stringify(data) , // 不用JSON.stringify()
headers: {
'Authorization': 'Bearer ' + getToken // 只要call api 要加header 的授權
},
success: function(response){
console.log("SUCCESS",response);
},
error: function(response){
console.log("ERROR",response);
}
});
}
function editRow(data) {
const getToken = localStorage.getItem("token")
console.log("GET TOKEN", getToken)
//// EDIT 的api ///
console.log("EDIT=====", data);
$.ajax({
url: "http://192.168.01.10:3000/api/item/status", /// api change ///
type:'PUT', // aka update or edit
dataType : 'json',
contentType : 'application/json; charset=UTF-8', // 不能用 'application/json; charset=utf-8'
data :JSON.stringify(data) , // 不用JSON.stringify()
headers: {
'Authorization': 'Bearer ' + getToken // 只要call api 要加header 的授權
},
success: function(response){
console.log("SUCCESS",response);
},
error: function(response){
console.log("ERROR",response);
}
})
// .then(res => console.log("RES", res));
}
$(function() {
$('#exampleModal').on('show.bs.modal', function(e) {
$('.modalTextInput').val('');
let btn = $(e.relatedTarget); // e.related here is the element that opened the modal, specifically the row button
let id = btn.data('id'); // this is how you get the of any `data` attribute of an element
$('.saveEdit').data('id', id); // then pass it to the button inside the modal
})
$('.saveEdit').on('click', function() {
let id = $(this).data('id'); // the rest is just the same
saveNote(id);
$('#exampleModal').modal('toggle'); // this is to close the modal after clicking the modal button
})
})
function saveNote(id) {
let text = $('.modalTextInput').val();
$('.recentNote').data('note', text);
console.log($('.recentNote').data('note'));
console.log(text + ' --> ' + id);
}
</script>
<script>
var storedItem = localStorage.getItem("storedItem") || [];
function save() {
var itemValue_device_id = document.getElementById("input_edit_device_id").value || "";
var itemValue_edit_name = document.getElementById("input_edit_name").value || "";
console.log("itemValue_device_id", itemValue_device_id, typeof(itemValue_device_id));
console.log("itemValue_edit_name", itemValue_edit_name, typeof(itemValue_edit_name));
let send_Reset_API_Data = {
device_id:itemValue_device_id,
port:itemValue_data_port,
}
if (Selected_add_edit_api === "add-api") {
AddRow(send_Reset_API_Data); // 執行程式 AddRow
console.log("send_Reset_API_Data", send_Reset_API_Data);
} else {
console.log("Invalid value for send_Reset_API_Data");
}
}
</script>
</body>
</html>
答: 暂无答案
评论