Ajax + Flask 用于通知下拉列表



我正在尝试实现通知下拉列表。 我正在使用 ajax 函数,它应该获取所有通知的 json 化数据并更新通知数量,而无需刷新页面。 但是,该功能不起作用,我没有得到任何输出。

我的烧瓶路线:

@bp.route('/notifications')
@login_required
def notifications():
since = request.args.get('since', 0.0, type=float)
notifications = current_user.notifications.filter(
Notification.timestamp > since).order_by(Notification.timestamp.asc())
return jsonify([{
'name': n.name,
'data': n.get_data(),
'timestamp': n.timestamp
} for n in notifications])

还有我的网页:

{% extends 'bootstrap/base.html' %}    
{% block navbar %}
<nav class="navbar navbar-default">
<div class="container">
<ul class="nav navbar-nav navbar-right">
{% if current_user.is_anonymous %}
<li>
<a role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Notifications {% set new_notifications = current_user.new_notifications() %}
<span id="message_count" class="badge"
style="visibility: {% if new_notifications %} visible
{% else %} hidden {% endif %};">
{{ new_notifications }}
</span>
</a>
<div class="dropdown-menu" aria-labelledby="dropdownMenuLink" id="dropdown">
<a class="dropdown-item" href="#">Action</a> 
</div>

</li>
{% endif %}
</ul>
</div>
</nav>
<script>
function set_message_count(n) {
$('#message_count').text(n);
$('#message_count').css('visibility', n ? 'visible' : 'hidden');
}
{% if current_user.is_authenticated %}
$(function() {
var since = 0;
setInterval(function() {
$.ajax('{{ url_for('main.notifications') }}?since=' + since).done(
function(notifications) {
for (var i = 0; i < notifications.length; i++) {
if (notifications[i].name == 'unread_notifications_count'){
set_message_count(notifications[i].data);
since = notifications[i].timestamp;}
else {
let choice = document.createElement("a");
let body = document.createTextNode("this is me");
choice.appendChild(body);
dropdown.appendChild(choice);
}
}
}
);
}, 10000);
});
{% endif %}
</script>
{% endblock %}

我哪里弄错了? 感谢您的帮助。

烧瓶路线示例:

@app.route('/example')
def example():
email = request.args.get('email', 404)
new_email = example_function(email)
return jsonify(res=new_email)

JS部分:

$.getJSON('/example', {
email: "example@example.com"
}, function (data) {
//data that flask returned
});

最新更新