具有 AJAX 功能的 HTML 按钮什么都不做
HTML button with AJAX function does nothing
我正在使用 Python、Flask 和 Mysql 开发 Web 应用程序。为了在不刷新页面的情况下刷新数据,我创建了一个 api 端点,其中 returns 所有数据都采用 JSON 格式,然后将其填充到 html 页面上使用 AJAX,但它不起作用。
代码如下:
*API 即 returns JSON
@app.route('/api/all_posts')
def get_all_posts():
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM lost_pets')
lost = list(cursor.fetchall())
cursor.execute('SELECT * FROM found_pets')
found = list(cursor.fetchall())
cursor.close()
return jsonify({"lost": lost, "found": found})
JSON 看起来像这样:
{
"found": [
{
"barrio": "Centro",
"calle_1": "Av. Uruguay",
"calle_2": "Ejido",
"created_at": "2022-02-27 15:37:19",
"fecha": "Sun, 27 Feb 2022 00:00:00 GMT",
"foto": "e932de86-4e1a-4a3a-9dc1-2d13059182c7.jpg",
"hora": "12:37",
"id": "found1db9dc00-cea1-4e8e-bb40-c0f91012401d",
"mascota": "gato"
}
],
"lost": [
{
"barrio": "Tres Cruces",
"calle_1": "Bulevar Artigas",
"calle_2": "Av. Italia",
"created_at": "2022-02-27 00:53:55",
"fecha": "Wed, 16 Feb 2022 00:00:00 GMT",
"foto": "2d3c7c2f-7d4f-49b6-bb1b-e8a329148668.jpg",
"hora": "15:59",
"id": "lost4bfe723a-ab6b-4818-b9d3-a34a72f93ee2",
"mascota": "perro",
"nombre": "Señor M"
}
]
}
*路由到 HTML 文件
@app.route('/landing')
def landing():
return render_template('index2.html')
*HTML 文件
{% extends "base.html" %}
{% block head %}
<link rel="stylesheet" href="{{ url_for('static', filename='styles/index.css') }}">
<title>EncuentraMe</title>
{% endblock %}
{% block body %}
<div class="feed">
<div class="filters">
<div class="filter">
<button type="button" class="btn btn-success btn-sm" id="all" onclick="refreshFeed()">Todos</button>
<button type="button" class="btn btn-outline-success btn-sm" id="lost">Perdidos</button>
<button type="button" class="btn btn-outline-success btn-sm" id="found">Encontrados</button>
</div>
<div class="post">
<a href="lost_pet" target="_blank" class="btn btn-primary" role="button">Publicar</a>
</div>
</div>
<article class="posts">
</article>
</div>
<script src="{{ url_for('static', filename='js/index.js') }}"></script>
<script src="{{ url_for('static', filename='js/populate.js') }}"></script>
{% endblock %}
*最后,AJAX 代码
$(document).ready(function () {
async function fetchAllPosts() {
const response = await fetch('http://localhost:5000/api/all_posts');
const data = await response.json();
return (data);
}
async function refreshFeed() {
fetchAllPosts().then(function (data) {
$.each(data.lost, function () {
let postLostNew = $(document.createElement('div'));
postLostNew.attr('id', 'lost');
postLostNew.addClass('pet');
postLostNew.addClass('pet_lost');
postLostNew.append('<p>¡Se busca a ' + this.nombre + '! Perdido/a desde el día '
+ this.fecha + ' última vez visto en las inmediaciones de ' + this.calle_1 +
' y ' + this.calle_2 + ' barrio ' + this.barrio + ' a las ' + this.hora + ' horas.\n'
+ 'Si lo viste por favor comunícate con Usuario.</p>');
postLostNew.append('<a href="/' + this.id + '"></a>');
postLostNew.find('a').append('<img src="static/images/' + this.foto + '">');
$('article.posts').append(postLostNew);
});
$.each(data.found, function () {
let postFoundNew = $(document.createElement('div'));
postFoundNew.attr('id', 'found');
postFoundNew.addClass('pet');
postFoundNew.addClass('pet_found');
postFoundNew.append('<p>Se encontró el día ' + this.fecha + ' por barrio '
+ this.barrio + ' en las inmediaciones de ' + this.calle_1 +
' y ' + this.calle_2 + ' a las ' + this.hora + ' horas.\n'
+ 'Si es tuyo o sabes de quien puede ser por favor comunícate con Usuario.</p>');
postFoundNew.append('<a href="/' + this.id + '"></a>');
postFoundNew.find('a').append('<img src="static/images/' + this.foto + '">');
$('article.posts').append(postFoundNew);
});
});
}
refreshFeed();
});
数据填充得很好,问题是,当我按下“待办事项”按钮时,它应该获取 JSON API 并刷新提要中的数据,而无需刷新页。但它什么也没做。
如果您需要我的任何其他代码,请告诉我。
也许该函数不能用作全局变量 - 尝试将 function refreshFeed()
替换为 window.refreshFeed = function()
我正在使用 Python、Flask 和 Mysql 开发 Web 应用程序。为了在不刷新页面的情况下刷新数据,我创建了一个 api 端点,其中 returns 所有数据都采用 JSON 格式,然后将其填充到 html 页面上使用 AJAX,但它不起作用。
代码如下: *API 即 returns JSON
@app.route('/api/all_posts')
def get_all_posts():
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM lost_pets')
lost = list(cursor.fetchall())
cursor.execute('SELECT * FROM found_pets')
found = list(cursor.fetchall())
cursor.close()
return jsonify({"lost": lost, "found": found})
JSON 看起来像这样:
{
"found": [
{
"barrio": "Centro",
"calle_1": "Av. Uruguay",
"calle_2": "Ejido",
"created_at": "2022-02-27 15:37:19",
"fecha": "Sun, 27 Feb 2022 00:00:00 GMT",
"foto": "e932de86-4e1a-4a3a-9dc1-2d13059182c7.jpg",
"hora": "12:37",
"id": "found1db9dc00-cea1-4e8e-bb40-c0f91012401d",
"mascota": "gato"
}
],
"lost": [
{
"barrio": "Tres Cruces",
"calle_1": "Bulevar Artigas",
"calle_2": "Av. Italia",
"created_at": "2022-02-27 00:53:55",
"fecha": "Wed, 16 Feb 2022 00:00:00 GMT",
"foto": "2d3c7c2f-7d4f-49b6-bb1b-e8a329148668.jpg",
"hora": "15:59",
"id": "lost4bfe723a-ab6b-4818-b9d3-a34a72f93ee2",
"mascota": "perro",
"nombre": "Señor M"
}
]
}
*路由到 HTML 文件
@app.route('/landing')
def landing():
return render_template('index2.html')
*HTML 文件
{% extends "base.html" %}
{% block head %}
<link rel="stylesheet" href="{{ url_for('static', filename='styles/index.css') }}">
<title>EncuentraMe</title>
{% endblock %}
{% block body %}
<div class="feed">
<div class="filters">
<div class="filter">
<button type="button" class="btn btn-success btn-sm" id="all" onclick="refreshFeed()">Todos</button>
<button type="button" class="btn btn-outline-success btn-sm" id="lost">Perdidos</button>
<button type="button" class="btn btn-outline-success btn-sm" id="found">Encontrados</button>
</div>
<div class="post">
<a href="lost_pet" target="_blank" class="btn btn-primary" role="button">Publicar</a>
</div>
</div>
<article class="posts">
</article>
</div>
<script src="{{ url_for('static', filename='js/index.js') }}"></script>
<script src="{{ url_for('static', filename='js/populate.js') }}"></script>
{% endblock %}
*最后,AJAX 代码
$(document).ready(function () {
async function fetchAllPosts() {
const response = await fetch('http://localhost:5000/api/all_posts');
const data = await response.json();
return (data);
}
async function refreshFeed() {
fetchAllPosts().then(function (data) {
$.each(data.lost, function () {
let postLostNew = $(document.createElement('div'));
postLostNew.attr('id', 'lost');
postLostNew.addClass('pet');
postLostNew.addClass('pet_lost');
postLostNew.append('<p>¡Se busca a ' + this.nombre + '! Perdido/a desde el día '
+ this.fecha + ' última vez visto en las inmediaciones de ' + this.calle_1 +
' y ' + this.calle_2 + ' barrio ' + this.barrio + ' a las ' + this.hora + ' horas.\n'
+ 'Si lo viste por favor comunícate con Usuario.</p>');
postLostNew.append('<a href="/' + this.id + '"></a>');
postLostNew.find('a').append('<img src="static/images/' + this.foto + '">');
$('article.posts').append(postLostNew);
});
$.each(data.found, function () {
let postFoundNew = $(document.createElement('div'));
postFoundNew.attr('id', 'found');
postFoundNew.addClass('pet');
postFoundNew.addClass('pet_found');
postFoundNew.append('<p>Se encontró el día ' + this.fecha + ' por barrio '
+ this.barrio + ' en las inmediaciones de ' + this.calle_1 +
' y ' + this.calle_2 + ' a las ' + this.hora + ' horas.\n'
+ 'Si es tuyo o sabes de quien puede ser por favor comunícate con Usuario.</p>');
postFoundNew.append('<a href="/' + this.id + '"></a>');
postFoundNew.find('a').append('<img src="static/images/' + this.foto + '">');
$('article.posts').append(postFoundNew);
});
});
}
refreshFeed();
});
数据填充得很好,问题是,当我按下“待办事项”按钮时,它应该获取 JSON API 并刷新提要中的数据,而无需刷新页。但它什么也没做。
如果您需要我的任何其他代码,请告诉我。
也许该函数不能用作全局变量 - 尝试将 function refreshFeed()
替换为 window.refreshFeed = function()