前端从后端动态获取数据,显示到html表格,并实现翻页,前端使用html编写,后端使用js,后端读取csv文件数据

前端做了三个界面,第一个index.html首页,可以选择查看的是哪一个csv的文件

第二给界面与第三个界面相似:

 

 

注意:数据表格界面可以进行翻页,红标为当前页,也可以输入多少页进行页面跳转 

 

 1.index.html代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://s3.pstatp.com/cdn/expire-1-M/jquery/3.2.1/jquery.min.js"></script>
    <title>文件选择</title>
</head>
<style>
    #title{
        text-align: center;
    }
    #table {
            width: auto;
            margin:  auto;
            border: 1px solid rgb(22, 129, 36);
            text-align: center;
        }

        #table th {
            height: auto;
            border: 1px solid rgb(22, 129, 36);
            text-align: center;
        }

        #table td {
            height: auto;
            border: 1px solid rgb(22, 129, 36);
            text-align: center;
        }
        button {
            padding: 10px;
            margin: 10px;
            box-shadow: 0 0 10px rgb(21, 146, 10);
        }
</style>
<body>
    <div id="title">
        <h1>文件选择<h1>
    </div>
    <div>
        <table id="table">
            <thead>
                <th>序号</th>
                <th>文件名</th>
                <th>操作</th>
            </thead>
            <tbody id="showfilebody">
        <table>
    </div>
    <script>
        
        $.ajax({
            url:"http://127.0.0.1:8000/index",
            dataType:'json',
            type:'get',
            success:function(data){
                var dataStr = JSON.stringify(data);
                data = $.parseJSON(dataStr);
                writelist(data);
            },
            error :function(arg1){
                alert("加载数据失败");
                console.log(arg1);
            }
        })
    function writelist(data){
        var showfilebody=document.getElementById('showfilebody');
        var tdstr='';
        for(var i=0;i<data.length;i++){
           
            tdstr+='<td>'+parseInt(i+1)+'</td>';
            tdstr+='<td>'+data[i]+'</td>';
            if(i==0){
                var but1="<button onClick='openAppleStore()'>查看</button>";
            }else if(i==1)
            {
                var but1="<button id='s'+i onClick='opengoogleplaystore()'>查看</button>";
            }
            
            tdstr+='<td>'+but1+'</td>';
            tdstr=tdstr+'</tr>';
            
        }
        
        showfilebody.innerHTML=tdstr;
    }
    function openAppleStore(){
        window.open("showAppleStore.html");//页面跳转
    }
    function opengoogleplaystore(){
        window.open("showgoogleplaystore.html");
    }
    </script>
</body>
</html>

在index界面中可以点击查看按钮跳转到对应的数据查看的按钮。

2.showAppleStore.html界面代码  showgoogleplaystory.html 代码相似就不贴了

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script>
    <title>AppleStore.csv数据展示</title>
</head>
<style>
    .tableCls, .tableCls td{
            border: 1px solid rgb(22, 129, 36);
            border-collapse: collapse;
            text-align: center;
        }
    #pagination {
            text-align: center;
            margin: 10px;
        }

        #table {
            width: auto;
            margin:  auto;
            border: 1px solid rgb(22, 129, 36);
            text-align: center;
        }

        #table th {
            height: auto;
            border: 1px solid rgb(22, 129, 36);
            text-align: center;
        }

        #table td {
            height: auto;
            border: 1px solid rgb(22, 129, 36);
            text-align: center;
        }

        #title {
            text-align: center;
        }
        
        button {
            padding: 10px;
            margin: 10px;
            box-shadow: 0 0 10px rgb(21, 146, 10);
        }
        #searchPage{
            padding: 10px;
            margin: 10px;
            width: 30px;
            box-shadow: 0 0 5px rgb(21, 146, 10);
        }
        
</style>
<body>
    <div id="title">
        <h2>AppleStore.csv数据展示</h2>
    </div>
    <table id="table" >
        <thead>
            <th>序号</th>
            <th>id</th>
            <th>track_name</th>
            <th>size_bytes</th>
            <th>currency</th>
            <th>price</th>
            <th>currency</th>
            <th>rating_count_tot</th>
            <th>user_rating</th>
            <th>user_rating_ver</th>
            <th>ver</th>
            <th>cont_rating</th>
            <th>prime_genre</th>
            <th>sup_devices.num</th>
            <th>ipadSc_urls.num</th>
            <th>lang.num</th>
            <th>vpp_lic</th>
        </thead>
        <tbody id="tdbody">

        </tbody>
        
            
            
    </table>
    
    <div id="pagination">
        <button id="prev">《</button>
        <button id="firstpageBtn">1</button>
        <button id="currentBtn">1</button>
        <button id="secondBtn">2</button>
        <button id="thirdBtn">3</button>
        <b>...</b>
        <button id="next">》</button>
        <d>跳转到<input id="searchPage"><d>页</d></input></d>
        <button id="actionBtn">跳转</button>
        <d id="showtotalpage">总页数:</d>
    </div class>
    <script>

    var totalPage;
    var currentPage=1;

    function main(){
        getdata(currentPage);
    }
    main();


/*
从服务器获取数据 
 */
function getdata(pageNum){
        $.ajax({
        url : "http://127.0.0.1:8000/AppleStore",//后台请求的数据
        data: {
            pageNum: pageNum //请求获取数据的页数 如获取第三页数据 pageNum=3
        },
        dataType: 'json', //数据格式
        type : "get",//请求方式
        success : function(data) {   
                //推荐这种方式
                var dataStr = JSON.stringify(data);
                data = $.parseJSON(dataStr);
                totalPage=data.totalPage;
                writeFrom(data);
                changePageText();
            },
            error : function (arg1) {
                alert("加载数据失败");
                console.log(arg1);
                }
              })
    }
//将数据写入表格
    function writeFrom(data){
        var tbody = document.getElementById('tdbody'); 
        var mytable=document.getElementById('table');
        var columm=mytable.rows[0].cells.length;//获取表头列数
        
            var rowStr = "";  //行的字符串的代码
            var k=1;
            for(var j=0;j<data.data.length;j++){
                var tdStr = "";
                for(var i=0;i<columm-1;i++)
                {  
                    if(i==0){
                        tdStr+="<td>"+k+"</td>";
                    }
                    tdStr += "<td>"+data.data[j][i]+"</td>";
                }
                k++;
                rowStr = rowStr + tdStr + "</tr>"; 
            }
            tbody.innerHTML=rowStr; 
    }

    //绑定向前翻页事件
    prev.onclick = function () {
            if (currentPage > 1) {
                currentPage--;
                getdata(currentPage);
                changePageText();
            } else {
                alert('当前为第一页!')
            }
        }

    currentBtn.onclick = function () {
        
        alert("显示页为当前页");
    
    }
    secondBtn.onclick = function () {
        var st=document.getElementById('secondBtn').textContent;
        currentPage=parseInt(st);
        getdata(st);
    }
    thirdBtn.onclick = function () {
        var st=document.getElementById('thirdBtn').textContent;
        currentPage=parseInt(st);
        getdata(st);
    }

    //绑定向后翻页事件
    next.onclick = function () {
        console.log("总页数:"+totalPage);
        if (currentPage <= totalPage) {
            currentPage++;
            getdata(currentPage);
            changePageText();
        } else {
            alert('当前为最后一页!')
        }
    }
    firstpageBtn.onclick = function () {
        currentPage=1;
        getdata(currentPage);
        changePageText(); 
    }
//输入框跳转特定页
    actionBtn.onclick = function () {
        var st=document.getElementById('searchPage').value;
        st=parseInt(st);
        if(st>0&&st<totalPage+1)
        {
            currentPage=st;
            getdata(currentPage);
            changePageText();
        }else{
            alert("此页不存在");
        }
        
    }
     //更改页标显示  
    function changePageText(){
        var isShowfirst=document.getElementById("firstpageBtn");
        var isShowsecond=document.getElementById("secondBtn");
        var isShowthird=document.getElementById("thirdBtn");
       
        if(currentPage>0&&currentPage<totalPage+1)
        {
            $('#currentBtn').text(currentPage);
            $('#showtotalpage').text("总页数:"+totalPage);
            document.getElementById('currentBtn').style.color='#ff3333';
            $('#secondBtn').text(currentPage+1);
            $('#thirdBtn').text(currentPage+2);
            if(currentPage==1)
            { 
                isShowfirst.style.display="none"
                isShowsecond.style.display="inline-block";
                isShowthird.style.display="inline-block";
            }
            else if(currentPage==totalPage)
            {
                isShowfirst.style.display="inline-block";
                isShowsecond.style.display="none";
                isShowthird.style.display="none";
            }
            else if(currentPage==totalPage-1){
                isShowfirst.style.display="inline-block";
                isShowsecond.style.display="inline-block";
                isShowthird.style.display="none";
            }else{
                isShowfirst.style.display="inline-block";
                isShowsecond.style.display="inline-block";
                isShowthird.style.display="inline-block";
            }
        }else{
            alert("不存在此页");
        }
        
    }
    $(document).ready(function(){
        $('searchPage').keydown(function(event){
            if(event.keyCode=13){
                alert(document.getElementById('searchPage').textContent);
                alert('sss');
            }
        })
    })
    </script>
</body>
</html>

3.后端使用js +express编写 先异步解析csv文件,存到内存中,接受前端请求,将相应的数据传到前端。后端使用的跨域模块需要自行下载 npm install cors --save  就可以

server.js代码如下:

//const csv = require('csvtojson')
var express=require('express')
let cors = require('cors')
//这种解析csv文件有时会出现json对象包含json对象,数据发送到前端后不宜处理
// const converter = csv()
//     converter.fromFile('/home/hezhu/下载/AppleStore.csv')
//     converter.then((json1) => {
//       console.log(json1[0]);
//       global.json=json1;
//       //异步操作、获取到csv数据之后在启动服务器
//       startServer();
//   })
//此篇中使用的是将csv读取的数据转化为数字储存,异步读取两个csv文件
var fs = require("fs");
const { table } = require('console');
var AppleStorefinalarr=new Array;
var AppleStoretotalPage;
var googleplayfinalarr=new Array;
var googleplaytotalPage;

async function main(){
    await readAppleStore();
    await readgoogleplaystore();
    await startServer();
}
main();


async function readAppleStore(){
    fs.readFile('AppleStore.csv', function (err, data) {
        var table = new Array();
        if (err) {
            console.log(err.stack);
            return;
        }
    
        ConvertToTable(data, function (table) {
            //丢弃表头
            var j=0;
            for(var i=1;i<table.length-1;i++){
                AppleStorefinalarr[j++]=table[i];
            }
            AppleStoretotalPage=Math.ceil(AppleStorefinalarr.length/25);//向上取整获取数据总页数
            console.log(AppleStoretotalPage);//每页25条数据
            //startServer();
        })
    });
    console.log("程序执行完毕1");
}

function readgoogleplaystore(){
    fs.readFile('googleplaystore.csv', function (err, data) {
        var table = new Array();
        if (err) {
            console.log(err.stack);
            return;
        }
        ConvertToTable(data, function (table) {
            //丢弃表头
            var j=0;
            for(var i=1;i<table.length-1;i++){
                googleplayfinalarr[j++]=table[i];
            }
            googleplaytotalPage=Math.ceil(googleplayfinalarr.length/25);//向上取整获取数据总页数
            console.log(googleplaytotalPage);//每页25条数据
            //startServer();
        })
    });
    console.log("程序执行完毕2");
}


function ConvertToTable(data, callBack) {
    data = data.toString();
    var table = new Array();
    var rows = new Array();
    rows = data.split("\r\n");
    for (var i = 0; i < rows.length; i++) {
//因为数据中存在双引号,双引号中含有逗号
        table.push(rows[i].split(/,s*(?![^"]*"\,)/));//以双引号以外的逗号对数据进行分隔
        //std=std.split(/,s*(?![^"]*"\,)/);
    }
    callBack(table);
}

var app=express();
app.use(cors())
//根目录
app.get('/AppleStore',function(req,res){
    console.log(req.query.pageNum)
    //console.log("欢迎进入nodejs");
    var nowArray=new Array;
   
    var j=0;
    nowArray=[];
    for(var i=(req.query.pageNum-1)*25;i<25*req.query.pageNum;i++) {
        if(AppleStorefinalarr[i]!=null){
            nowArray[j++]=AppleStorefinalarr[i];
        }
        
    }
//每一次数据发送都包含流了当页数据与总页数
    var data={
        totalPage:AppleStoretotalPage,
        data:nowArray
    }
    res.send(data);
    
})

app.get('/index',function(req,res){
    
    var nowArray=new Array;
    nowArray=[];
    nowArray[0]="AppleStore.csv";
    nowArray[1]="googleplaystore.csv";
    res.send(nowArray);
    
})

app.get('/googleplaystore',function(req,res){
    console.log(req.query.pageNum)
    //console.log("欢迎进入nodejs");
    var nowArray=new Array;
   
    var j=0;
    nowArray=[];
    for(var i=(req.query.pageNum-1)*25;i<25*req.query.pageNum;i++) {
        if(googleplayfinalarr[i]!=null){
            nowArray[j++]=googleplayfinalarr[i];
        }
        
    }
    var data={
        totalPage:googleplaytotalPage,
        data:nowArray
    }
    res.send(data);
    
})




//服务器主体函数
function startServer(){
    var server=app.listen(8000,function(req,res){
        var host=server.address().address
        var port=server.address().port
        console.log("访问地址为 http://%s:%s", host, port)
    })
}



  • 10
    点赞
  • 69
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 前端登录页面可以通过如下几种方法将数据传到下一个页面: 1. 使用 URL 参数:在跳转到下一个页面时,将数据附加到 URL 上。 2. 使用 localStorage 或 sessionStorage:可以在登录页面中将数据存储到 localStorage 或 sessionStorage 中,然后在下一个页面中读取这些数据。 3. 使用 React 状态管理工具:如果你使用了 React 框架,你可以使用状态管理工具,如 Redux 或 Mobx,将数据存储到状态管理工具中,然后在下一个页面中读取这些数据。 4. 使用 Cookies:可以在登录页面中将数据存储到 Cookies 中,然后在下一个页面中读取这些数据。 这几种方法都有自己的优缺点,根据你的需求选择合适的方法即可。 ### 回答2: 前端登录页面从后端获取的数据可以通过以下几种方式将数据传递到下一个页面: 1. 使用URL参数传递:在登录页面从后端获取到数据后,可以将数据作为参数添加到下一个页面的URL中,例如:`nextpage.html?data=value`,然后通过JavaScript获取URL参数解析数据,在下一个页面进行使用。 2. 使用表单提交:可以将后端获取到的数据绑定到一个隐藏的表单字段中,然后在登录页面的表单提交时,将这些数据一并提交到下一个页面。下一个页面使用JavaScript后端代码获取表单字段的值来获取数据。 3. 使用本地存储:前端可以使用本地存储(如浏览器的localStorage或sessionStorage)将后端获取到的数据保存起来,在下一个页面中再从本地存储中读取数据使用。 4. 使用全局变量:前端可以将后端获取到的数据保存在一个全局变量中,在下一个页面中引用该全局变量来获取数据。 5. 使用AJAX请求:前端可以使用AJAX请求将后端获取到的数据发送到下一个页面,然后在下一个页面中通过接收AJAX请求的方式来获取数据。 需要根据具体的应用场景和需求选择合适的方式来传递数据。 ### 回答3: 前端登录页面从后端获取的数据可以通过多种方式传递到下一个页面。以下是一些常用的方法: 1. 使用URL参数传递:将数据作为URL参数附加到下一个页面的URL中。例如,可以使用JavaScript的`encodeURIComponent()`函数对数据进行编码,然后将其添加到URL中。在下一个页面中,可以使用`decodeURIComponent()`函数解码并获取传递的数据。 2. 使用表单提交:将数据存储在一个隐藏的表单字段中,并在表单提交时将其发送到下一个页面。在下一个页面中,可以通过表单的名称或ID来获取传递的数据。通常使用POST方法进行表单提交,以确保数据的安全性。 3. 使用本地存储:在登录页面使用浏览器提供的本地存储机制(如localStorage或sessionStorage)将数据保存在客户端。然后在下一个页面中,可以通过读取本地存储中的数据来获取登录页面传递的数据。 4. 使用cookie:在登录页面将数据存储在cookie中,并在下一个页面中读取cookie来获取传递的数据。请注意,cookie在网站间传递,因此对于敏感数据,需要采取适当的加密和安全措施。 无论使用哪种方法,都需要在接收数据的页面进行相应的处理来获取传递过来的数据,并根据需要进行展示或其他操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值