首页 > 解决方案 > 如何将 node.js 数组变量传递给 jquery 以在 html 表中显示这些值?

问题描述

我的 node.js 文件中有一个数组变量。我试图在我的 html 前端页面上以表格形式显示这个数组的值。那么我怎样才能将此数组变量发送到 jquery/javascript 以便我可以追加像这样 $('body').html(string)。

出.txt

IMAGE                  STATUS        NAMES
k8s.gcr.io/pause:3.1   Up 2 days     k8s_POD   Deploy  Decomission Properties
eb516548c180           Up 2 days     k8s_cor   Deploy  Decomission Properties


index.js

var fs = require('fs');
fs.readFile('out.txt', function(err, data) {
    if(err) throw err;
    var array = data.toString().split(/\s+/);
    for(i in array) {
        console.log(array[i]);
    }
});

尝试做一些与下面提到的代码非常相似的事情,但 index.js 文件中存在 node.js 数组变量。

var html = '<table class="table table-striped">';
  $.each(data, function(index, value){
         html += '<tr>';
        $.each(value, function(index2, value2){
            html += '<td>'+value2+'</td>';
        });
        html += '<tr>';
     });
     html += '</table>';
     $('body').html(html);

如何相应地修改我的代码以将数组变量从 index.js 发送到前端 javascript 或 jquery。我想我必须为此使用 ajax。一旦发送了变量,我将如何 $('body').html 或以表格方式将其附加到我的 html 页面。请帮助。

标签: jqueryhtmlnode.js

解决方案


由于您在成功回调中使用了一个字符串数组,因此您正在尝试迭代value但它是一个字符串而不是另一个数组。您没有指定 out.txt 的内容,所以我认为它类似于:

出.txt

test1 test2 test3 test4

我在一个非常简单的服务器上包含了用于读取文件的代码:调用http://localhost:3000/将导致['test1','test2','test3','test4']

服务器.js

const http = require('http');
var fs = require('fs');

const hostname = '0.0.0.0';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'application/json');
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
  fs.readFile('out.txt', function(err, data) {
    if(err) throw err;
    var array = data.toString().split(/\s+/);
    res.end(JSON.stringify(array));
    });

});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

我更改了 HTTP GET 成功回调,因为您有一个字符串数组,所以内容value是字符串本身而不是另一个字符串数组,不需要内部foreach

索引.html

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $.get("http://localhost:3000", function(data, status){
    var html = '<table class="table table-striped">';
    $.each(data, function(index, value){
           html += '<tr>';
           html += '<td>'+value+'</td>';
           html += '</tr>';     
        });
     html += '</table>';

     $("#content").append(html);
    });
  });
});
</script>
</head>
<body>
    <div id="content"> </div>
    <button>GET Data</button>
</body>
</html>

更新

在服务器上提供 html 文件。

服务器.js

var express = require("express");
var fs = require("fs");
var app = express();
var path = require("path");
app.get('/',function(req,res){
   res.sendFile(path.join(__dirname+'/index.html'));
   //__dirname : It will resolve to your project folder.
});

app.get('/out', function(req,res){
    fs.readFile('out.txt', function(err, data) {
        if(err) throw err;
        var array = data.toString().split(/\s+/);
    res.type('json')
        res.end(JSON.stringify(array));
    });
});

app.listen(3000);
console.log("Server running at Port 3000");

索引.html

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

    $.get("/out", function(data, status){
        var html = '<table class="table table-striped">';
        $.each(data, function(index, value){
            html += '<tr>';
            html += '<td>'+value+'</td>';
            html += '</tr>';     
        });
        html += '</table>';
        $("#content").append(html);
    });
});
</script>
</head>
<body>
    <div id="content"> </div>
</body>
</html>

更新

使用新提供的 out.txt

服务器.js

var express = require("express");
var fs = require("fs");
var app = express();
var path = require("path");
app.get('/',function(req,res){
   res.sendFile(path.join(__dirname+'/index.html'));
   //__dirname : It will resolve to your project folder.
});

app.get('/out', function(req,res){
    fs.readFile('out.txt', function(err, data) {
        if(err) throw err;

        const array = [];
        var lines = data.toString().split('\n').filter((column) => column.length != 0);

        for(i=0; i<lines.length; i++) {
             array.push(lines[i].split('  ').filter((column) => column.length != 0))        
    }
    const response = {headers:array[0], rows:array.slice(1, array.length)}; 
        res.type('json')
        res.end(JSON.stringify(response));
    });
});

app.listen(3000);
console.log("Server running at Port 3000");

索引.html

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

    $.get("/out", function(data, status){
        var html = '<table class="table table-striped">';
    html += '<tr>'; 
    $.each(data.headers, function(index, value){            
            html += '<th>'+ value+'</th>';     
        });
    html += '</tr>';
        $.each(data.rows, function(index, line){
            html += '<tr>';
        $.each(line, function(index, value){        
                html += '<td>'+ value+'</td>';
            })
            html += '</tr>';     
        });
        html += '</table>';
        $("#content").append(html);
    });
});
</script>
</head>
<body>
    <div id="content"> </div>
</body>
</html>

更新

使用 docker ps 的输出而不是输出文件。

服务器.js

var express = require("express");
var fs = require("fs");
var app = express();
var path = require("path");
app.get('/',function(req,res){
   res.sendFile(path.join(__dirname+'/index.html'));
   //__dirname : It will resolve to your project folder.
});

app.get('/out', function(req,res){
const {execSync} = require('child_process');
let output = execSync("docker ps -a --format 'table {{.Names}}\\t{{.Status}}\\t{{.Image}}'", { encoding: 'utf8'});

     const array = [];
     var lines = output.toString().split('\n').filter((column) => column.length != 0);

     for(i=0; i<lines.length; i++) {
         array.push(lines[i].split('  ').filter((column) => column.length != 0))        
     }   
     const response = {headers:array[0], rows:array.slice(1, array.length)};    
     res.type('json')
     res.end(JSON.stringify(response));      
});

app.listen(3000);
console.log("Server running at Port 3000");

推荐阅读