正如 @Klaus D. 在评论部分中提到的,您想要实现的目标可以仅使用 Javascript 来完成。也许你的问题是
如何向服务器端发送请求(以获取或获取某些信息)并在客户端接收响应,而无需刷新页面,这与POST
方法通常是怎样的?
我将尝试解决上述问题,因为这可能就是您的情况。
一个潜在的解决方案
为此,请使用 Ajax。构建一个函数,将包含某些信息的有效负载发送到服务器,一旦收到响应,您就可以使用该数据动态修改您想要修改的网页部分。
让我们首先为问题构建正确的背景。假设您想按类别过滤一些项目,并让用户决定。这就是 AJAX 的思想,用户可以异步地从服务器发送和检索数据。
HTML(待修改的div)
<div class="row" id="construction-projects"></div>
JavaScript(客户端)
$.post('/search_pill', {
category: category, // <---- This is the info payload you send to the server.
}).done(function(data){ // <!--- This is a callback that is being called after the server finished with the request.
// Here you dynamically change parts of your content, in this case we modify the construction-projects container.
$('#construction-projects').html(data.result.map(item => `
<div class="col-md-4">
<div class="card card-plain card-blog">
<div class="card-body">
<h6 class="card-category text-info">${category}</h6>
<h4 class="card-title">
<a href="#pablo">${item.title_intro.substring(0, 40)}...</a>
</h4>
<p class="card-description">
${item.description_intro.substring(0, 80)}... <br>
<a href="#pablo"> Read More </a>
</p>
</div>
</div>
</div>
`))
}).fail(function(){
console.log('error') // <!---- This is the callback being called if there are Internal Server problems.
});
}
构建一个函数,通过 ajax 获取当前页面,但不是整个页面,只是从服务器获取有问题的 div。然后,数据将(再次通过 jQuery)放入同一 div 中,并用新内容替换旧内容。
Flask(服务器端)
''' Ajax path for filtering between project Categories. '''
@bp.route('/search_pill', methods=['POST'])
def search_pill():
category = request.form['category']
current_page = int(request.form['current_page'])
## Search in your database and send back the serialized object.
return jsonify(result = [p.serialize() for p in project_list])