【问题标题】:How to send data from server to client using AJAX?如何使用 AJAX 将数据从服务器发送到客户端?
【发布时间】:2012-12-15 23:09:49
【问题描述】:

我想查询 MongoDB 并检索一些文档。然后将这些文档流回客户端以填充 <table> 而无需刷新页面。我已经知道如何使用 socket.io 来做到这一点,但我想学习如何在没有套接字的情况下传输数据。我目前正在获得Failed to load resource: the server responded with a status of 404 (Not Found),因为我没有/loadRecent 资源,但我不知道如何在不加载新页面的情况下执行GET。 (我可能缺少一些关于 REST 工作原理的基本知识。)请指教。

服务器代码:

#Get recent documents
            app.get '/loadRecent', (req, res) ->
                console.log 'Documents requested...'
                db.collection 'documents', (err, collection) ->
                    collection.find().sort(dateAdded:-1) (err, cursor) ->
                        if not err
                            res.setHeader 'content-type':'application/json'
                            cursor.each (err, item) ->
                                res.write item
                        else
                            console.log 'Error getting recent docs: ' + err

客户端代码(现在只有一个console.log,但计划是在我得到数据流过后将数据附加到<table>。):

$.getJSON('/loadRecent', function(data, textStatus, jqXHR)
            {
                console.log('Data recieved from server: ' + data);
            });

【问题讨论】:

    标签: ajax node.js rest coffeescript


    【解决方案1】:

    尝试在每个游标中构建 JSON,而不是每次都尝试写入。

    构建 JSON,然后在光标为 NULL 时使用 res.send,这样您就知道构建完成了。

    【讨论】:

      猜你喜欢
      • 2015-05-23
      • 2020-02-28
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 2021-12-07
      • 2013-08-13
      • 2022-01-17
      • 2012-12-31
      相关资源
      最近更新 更多