【发布时间】:2014-02-27 03:02:55
【问题描述】:
这涉及一个带有 AJAX 调用的 Node/Express/MongoDB 应用程序
由于某种原因,
selector.html() 事件正在替换 选择器,但现在不是。
唯一的变化是在后端引入了editAll() 函数,它将MongoDB 数据传递到.get,在通过ajax 将其传递到前端之前进行一些计算。
而不是浏览器控制台写 GET http://localhost:9999/ 和每个 btn.click
[13:47:57.240] GET http://localhost:9999/ [HTTP/1.1 200 OK 5ms]
[13:47:57.174] "Getting All Actions"
[13:47:57.192] "value of action with index 0 = 4"
[13:47:57.193] "value of action with index 1 = 8"
[13:47:57.193] "value of action with index 2 = 9"
[13:48:03.704] GET http://localhost:9999/ [HTTP/1.1 200 OK 7ms]
[13:48:03.640] "Getting All Actions"
[13:48:03.661] "value of action with index 0 = 4"
[13:48:03.661] "value of action with index 1 = 8"
[13:48:03.661] "value of action with index 2 = 9"
.. 控制台为出现在前端的一组重复 div 写入一整套“响应”
[13:29:24.244] GET http://localhost:9999/ [HTTP/1.1 200 OK 5ms]
[13:29:24.182] "Getting All Actions"
[13:29:24.197] "value of doc with index 0 = 24"
[13:29:24.197] "value of doc with index 1 = 28"
[13:29:24.197] "value of doc with index 2 = 29"
...
[13:29:24.198] "value of doc with index 6 = 24"
[13:29:24.198] "value of doc with index 7 = 28"
[13:29:24.199] "value of doc with index 8 = 29"
据我所知,后端运行良好,因为唯一的 3 docs in the db 被传递给 eventAll() 函数,该函数再次提供相同的 3 docs。
function getAll(res) {
db.collection('demo').find().sort( { value: 1 } ).toArray(function (err, docs) {
console.log("Got the docs: " + utils.inspect(docs));
//res.json({docs: docs}); THIS WORKS PERFECTLY,
but the eventAll() pass causes this frontend issue
/* pass and rebuild the data array before we 'json' it */
var editedDocs = editAll(docs);
res.json({docs: editedDocs});
});
}
调用editAll()函数传递数据,是eventloop操作没有结束还是怎么回事?
function editAll(allDocs) {
var returnedValue = [];
for (var i=0, len=allDocs.length; i < len; ++i){
//does some calculations
var newVal = {_id:allDocs[i]._id,title:allDocs[i].title,value:allDocs[i].value};
returnedValue.push(newVal);
}
console.log(returnedValue);
return (returnedValue);
}
为什么每个btn.click 都会向#result 添加另一组div
这是通过 gotAllSuccess 在 btn.click 上构建一些 html 的 ajax .get 调用
$('#getBtn').click(function() {
console.log('Getting All');
$.get('http://localhost:9999').
done(gotAllSuccess).
fail(gotAllFailure);
});
function gotAllSuccess(result){
var docs = result.docs;
var html = '';
var doc;
for (var i=0, len=docs.length; i < len; i++){
doc = docs[i];
console.log("value of doc with index " + i + " = " + doc.value);
html += "<div class='rResult' id='rResult" + i + "'>"+doc.title+"</div><br>";
}
$('#result').html(html);
}
【问题讨论】:
-
首先,您应该检查在
editDocs调用后获得的文档数量。你能改写你的问题吗?它几乎不可读。乍一看,我看不出您的代码有任何问题。 -
@Mr_Mig 正在检查,之后会重新提出问题。感谢您的评论
-
@Mr_Mig 更新了问题,是不是更清楚了?在 editAll() 调用之前和之后只存在 3 个文档,但它们在前端被一遍又一遍地打印,on.btn.click!
-
我还有一些额外的问题: 1. 在 return 语句之前,
editAll函数中记录了什么? 2. 这就是你的 editAll 函数中的所有逻辑吗? -
1.返回的值数组记录在 editAll() 函数中,与从 db 传递的内容完全匹配。 2.此时,出于测试目的,这是editAll()函数中的所有逻辑..一旦工作,将会有一些计算(一次一步;)..
标签: javascript jquery html node.js mongodb