【问题标题】:Trouble sending AJAX GET request to mongodb向 mongodb 发送 AJAX GET 请求时遇到问题
【发布时间】:2014-04-22 19:47:04
【问题描述】:

我目前正在尝试使用 nodejs 和 express 在浏览器上显示来自 mongodb 集合的数据,并且我遇到了非常困难的时间。这是客户端的调用本身。

document.onload= $(function (e) {
var i = 0;
$.ajax({
    type: "GET",
    url: "http://localhost:3000/viewdata",
    dataType: "jsonp",
    jsonp: 'jsonp',
    success: function (responseData, status) {
       //code doing things with the data
    }

这是节点中发生的事情。

app.post('/viewdata', function(req, res){
    tweets.find({}, function (err, doc) {
        res.render('../../views/view.html', doc);   
    });
});

呼叫返回“200 OK”。我能够在控制台上查看来自 mongo 的数据,所以我知道数据在那里,但我不确定如何获取它并将其显示在浏览器上。感谢您的帮助

【问题讨论】:

  • 远射,但试试“res.render('view.html', doc);” (没有相对路径)
  • 相对路径是正确的,我没有设置视图,所以它是从当前文件位置开始的。我有代码的其他部分可以使用,所以我认为这不是问题。
  • 你说你得到了“200 OK”。当你console.log(responseData)时,你得到你想要的数据了吗?
  • 它永远不会到达成功函数,它无法发出请求,所以它转到我的失败函数通过报告来处理错误。

标签: javascript ajax node.js mongodb express


【解决方案1】:

对于任何寻找这个问题的答案的人来说,问题是我试图在发布请求中从服务器获取数据。我在 POST 请求下方发出了单独的 GET 请求,并将数据发送到视图。您现在可以使用 ajax 获取请求并在客户端使用数据。

app.get('/viewdata', function(req, res){
 tweets.find().toArray(function(err, items) {
    /*console.log(items);*/
    res.send(items);
    });
});

在客户端:

$.get("/viewdata", function(data) {
/*do stuff with the data*/
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 2018-09-13
    • 2020-02-08
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 2014-11-02
    相关资源
    最近更新 更多