从 Node.js 文件中获取数据并将其显示在 HTML/JS 页面中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18042087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:51:19  来源:igfitidea点击:

Getting Data from Node.js file and displaying it in HTML/JS page

javascripthtmlnode.js

提问by Wayne Rooney

I am new to Node.js and this is my first project with it. I have made a node.js file named test.js. It has an array say a.

我是 Node.js 的新手,这是我的第一个项目。我制作了一个名为 test.js 的 node.js 文件。它有一个数组说 a。

Now I want to make a HTML file that calls this test.js on button click event. Then get the data from that file and publish it on a table in the HTML file.

现在我想制作一个 HTML 文件,在按钮点击事件上调用这个 test.js。然后从该文件中获取数据并将其发布在 HTML 文件中的表上。

I have already written the node.js file and I can see the results on console.log(a). But I cant understand how to send this array to HTML when it will ask for it.

我已经编写了 node.js 文件,我可以在 console.log(a) 上看到结果。但是我无法理解如何在需要时将此数组发送到 HTML。

Meanwhile, I googled and made up some code. The request reaches the server but I always get error response from server. Why so?

同时,我用谷歌搜索并编写了一些代码。请求到达服务器,但我总是从服务器收到错误响应。为什么这样?

Client Side -

客户端 -

function fetch() {
    $.ajax({
    type: 'POST',
    url: "http://127.0.0.1:8888",
    data: 'China',
    datatype: 'json',
    success: function (data) {
        alert("hi");
        var ret = jQuery.parseJSON(data);
        $('#q').html(ret.msg);
    },
    error: function (xhr, status, error) {
        alert("hii");
    }
});

Server side :

服务器端 :

http.createServer(function(request, response) {  
    console.log("Request received");
    response.writeHeader(200, {"Content-Type": "application/json"}); 
    request.on('data', function (chunk) {
        console.log(chunk.toString('utf8'));
                    consol.log(result);
        response.write(JSON.stringify({data : result}));
    });     
    response.end();  
}).listen(8888);

I can see China on the console.But I dont get back the result array back to the client. Here result is an array and I get its value on the console. Just that I dont get it back to the client. Any help ?

我可以在控制台上看到china。但是我没有将结果数组返回给客户端。这里的结果是一个数组,我在控制台上得到它的值。只是我没有把它还给客户。有什么帮助吗?

回答by JohnP

You should start by setting up a server to serve requests. I use expressjs for this - http://expressjs.com/

您应该首先设置一个服务器来处理请求。我为此使用 expressjs - http://expressjs.com/

This will allow you to run nodejs as a web application.

这将允许您将 nodejs 作为 Web 应用程序运行。

Setup a route in express JS to serve your data - http://expressjs.com/api.html#express

在 express JS 中设置一个路由来提供您的数据 - http://expressjs.com/api.html#express

var express = require('express');
var app = express();

app.get('/data', function(req, res){
  res.send('hello world'); //replace with your data here
});

app.listen(3000);

Open up a browser, and type in http://MY_SERVER_ADDR:3000/dataand you should see your output there.

打开浏览器,输入http://MY_SERVER_ADDR:3000/data,你应该会在那里看到你的输出。

Next, you'll need to attach an even handler to your HTML file that will trigger a $.get() request when it is triggered. Add the previous url to your data in your $.get call and do something with it.

接下来,您需要将一个偶数处理程序附加到您的 HTML 文件中,该处理程序将在触发时触发 $.get() 请求。在 $.get 调用中将先前的 url 添加到您的数据中并对其进行处理。

$('.my_selector').click(function(){
   $.get('http://MY_SERVER_ADDR:3000/data', {}, function(data){
        console.log(data)
   });
});

That should get you going.

那应该能让你继续前进。

回答by Marc de Ruyter

After wrestling with the same question, i found that this is exactly where a template engine comes into the node-picture. EJS solved it for me, but there are many more available. This articlecompares 10 template engines.

在与相同的问题搏斗之后,我发现这正是模板引擎进入节点图片的地方。EJS 为我解决了这个问题,但还有更多可用的。该文章比较了10个模板引擎。