我刚刚完成了 MongoDB tutorial for nodejs在其网站上,我正在尝试构建一个非常简单的测试用例,用于通过 AJAX 将查询结果发送到 Google Chart。
这是我用来生成查询的 nodejs 文件:
代码:
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
MongoClient.connect('mongodb://localhost:27017/crunchbase', function(err, db) {
assert.equal(err, null);
console.log('The app is now running');
var query = {name: { $regex: /^m/}, founded_year: { $gte: 2009 }};
var projection = {name: 1, founded_year: 1, _id: 0};
var cursor = db.collection('companies').find(query);
cursor.project(projection);
});
我用来将光标加载到谷歌图表中的示例 comes from this page .
这是我用来生成图表的示例代码:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<!--Load the AJAX API for Google Charts- -->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "http://localhost:27017/crunchbase",
dataType: "jsonp",
asynchronous: true
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.Table(document.getElementById("chartDiv"));
chart.draw(data);
}
</script>
</head>
<body>
<h1 style="text-align: center">Companies Starting With "M" Founded After 2009</h1>
<div id="chartDiv">
</div>
</body>
</html>
我目前在控制台中收到此错误消息:
错误信息:
Uncaught SyntaxError: Unexpected identifier crunchbase?callback=jQuery1102076…_1481945533315&_=1481945533316:1
另请注意:我将 dataType
更改为 jsonp
并将 asynchronous
更改为 true
为了让错误消息消失,但这些与 Google Charts 示例给出的示例背道而驰,因此这可能是相关的。
如果我的代码有点粗糙,我深表歉意,这实际上只是试图将来自 MongoDB 和 Google Charts 文档的非常基本的示例拼凑在一起,并让它们发挥作用。
最佳答案
当asynchronous: true
--> 需要等待请求完成,
在尝试使用数据/绘制图表之前
查看 .done
-- 尝试以下代码片段...
google.charts.load('current', {'packages':['table']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
url: "http://localhost:27017/crunchbase",
dataType: "jsonp",
asynchronous: true
}).done(function (jsonData) {
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.Table(document.getElementById("chartDiv"));
chart.draw(data);
}).fail(function (jqXHR, textStatus, errorMessage) {
console.log(errorMessage);
});
}
关于jquery - 使用 AJAX/Jquery 使用 MongoDB 投影填充 Google Chart,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41195162/