【问题标题】:Display retrieved SQL data to HTML page in Node.js在 Node.js 中将检索到的 SQL 数据显示到 HTML 页面
【发布时间】:2013-02-11 13:51:45
【问题描述】:

我有从我们的数据库中检索数据集的代码:

var pg = require('pg').native;

// Format: "postgres://YourUserName:YourPassword@localhost:5432/YourDatabase";
var dbUrl = "url hidden";

function testConn(onDone) {
    pg.connect(dbUrl, function(err, client) {
        client.query("SELECT ad FROM alert WHERE ad = 132", function(err, result) {

            console.log("ad is: %d", result.rows.length);
            console.log("ad value is: %d", result.rows[0].ad_id );
            onDone();
        });
    });
}

// Let's call the function
testConn(disconnectAll)

// Disconnect all connections
function disconnectAll() {
    pg.end();
}

这很好用,它会检索结果并将结果显示到终端上。

我想要实现的是让这些结果出现在 html 页面而不是控制台上,我已经开发了前端页面(使用 jquery mobile)并希望数据库值出现在这个页面而不是控制台。

谁能指导我做这件事的正确道路?例如,我知道 div 元素可用于隐藏/显示数据,我只需要知道检索结果并将结果显示到 html 页面等元素上的最佳方法。

感谢所有帮助!

【问题讨论】:

  • 只要形成一个Json对象传给客户端,客户端应该可以解析和填充

标签: javascript html linux node.js postgresql


【解决方案1】:

类似这样的东西,但这只是谷歌的副本

  response.writeHead(200, {"Content-Type": "application/json"});
  var otherArray = ["item1", "item2"];
  var otherObject = { item1: "item1val", item2: "item2val" };
  response.write(
    JSON.stringify({ 
      anObject: otherObject, 
      anArray: otherArray, 
      another: "item",
    })
  );

【讨论】:

  • @JackSparrow ,您应该遍历您的数据库记录并形成一个 json 对象并最终字符串化并作为响应发送给客户端
  • 让它工作了,谢谢!我使用您建议的方法(json)创建了一个版本,只是为了练习,但后来又做了另一个版本输出到 html。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 2014-02-23
  • 2018-10-12
  • 1970-01-01
相关资源
最近更新 更多