我正在使用 Python、Flask 和 Mysql 開發一個 Web 應用程式。為了在不必重繪 頁面的情況下重繪 資料,我創建了一個 api 端點,它以 JSON 格式回傳所有資料,然后使用 AJAX 將其填充到 html 頁面上,但它不起作用。
代碼如下: *回傳 JSON 的 API
@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();
});
資料填充得很好,問題是,當我按下“Todos”按鈕時,它應該獲取 JSON API 并重繪 提要中的資料,而無需重繪 頁面。但它什么也沒做。
如果您需要我的任何其他代碼,請告訴我。
uj5u.com熱心網友回復:
也許該函式不能作為全域變數使用 - 嘗試替換function refreshFeed()為window.refreshFeed = function()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/433441.html
上一篇:在MySql上將字串排序為日期
下一篇:MySQL用變數更新
