【发布时间】:2020-04-20 17:30:48
【问题描述】:
所以我在 jQuery 中执行了一个 GET 请求,对于某些请求,它恰好执行了两次。第一次获得适当的数据,第二次获得空对象。因为那个空对象被传递到一个 EJS 文件中,所以我的代码抛出了一个错误。我真的不明白为什么会这样。我试图抓住空对象,但这使我的网络应用程序挂起。我试图绑定和点击事件,但无济于事。这是它正在生成的输出和我编写的代码。任何帮助表示赞赏
输出:
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Listening to port 8081
app.get
reply get requested
found
[
{
replies: [
'fight me bro',
'boss main',
'kinda slow innit'
],
_id: 5e0cb67b48dfda4448c57ec0,
msg: 'if you can',
likes: 2,
date: '1/1 @ 9:10',
seconds: 51,
__v: 0
}
]
reply get requested
found
[]
在第二个reply get requested可以看到,记录的对象是空的。
JQuery 代码
$('.bubble.sender.first.animate-bottom').on('click', function(){ // hit bubble to reveal replys
console.log("bubble clicked.");
var message = $(this).find('input.hiddentag').val(); // gets the message
var replydate = $(this).find('input.hiddendatetag').val(); // gets the date
console.log("message: " + message);
var chat = {msg: message, date: replydate};
console.log(chat);
$.ajax({
type: 'GET',
url: '/reply',
data: chat,
success: function(data){
console.log("Heading to appropriate reply page.....");
window.location.replace("/reply");
}
});
return false;
});
节点 JS 代码
app.get('/reply', function(req, res){
console.log("reply get requested");
// console.log("message: ", req.query);
chats.find({msg: req.query.msg, date: req.query.date}, function(err, data) {
if (err) {
console.log("couldn't find chat");
throw err // crash
}
console.log('found');
console.log(data);
res.render('reply', {chat: data});
})
})
EJS 代码:
<% for(var i = 0; i < chats.length; i++) { %> <!-- earlier chats go first-->
<% if (i % 2 == 0) { %>
<div class="bubble recipient first animate-bottom">
<li class = "display"><%= chats[i].msg %>
<i class="fas fa-heart liked" aria-hidden="true"></i> <sub><%=chats[i].likes%></sub>
<i class="fa fa-reply reply"></i>
<input type="hidden" id = "changeit" class = "likebutton" value = "<%=chats[i].likes%>" >
<input type="hidden" class = "hiddentag" value="<%=chats[i].msg%>"> <!-- needed to get the message that was liked-->
<input type="hidden" class = "hiddendatetag" value="<%=chats[i].date%>"> <!-- needed to filter messages that are the same-->
</li>
<br>
<span>Sent: <%=chats[i].date %> </span>
</div>
<% } else { %>
<div class="bubble sender first animate-bottom">
<li class = "display"><%= chats[i].msg %>
<i class="fas fa-heart liked" aria-hidden="true"></i> <sub><%=chats[i].likes%></sub>
<i class="fa fa-reply reply"></i>
<input type="hidden" id = "changeit" class = "likebutton fas fa-heart" value = "<%=chats[i].likes%>" >
<input type="hidden" class = "hiddentag" value="<%=chats[i].msg%>"> <!-- needed to get the message that was liked-->
<input type="hidden" class = "hiddendatetag" value="<%=chats[i].date%>"> <!-- needed to filter messages that are the same-->
</li>
<br>
<span>Sent: <%=chats[i].date %> </span>
</div>
<% } %>
<% } %>
【问题讨论】:
-
“气泡点击”消息在日志中只出现一次?