简体   繁体   English

如何使用 jquery + flask 请求更新 html 而无需重新加载网页?

[英]How to use jquery + flask to make a request to update html without reloading a webpage?

I am making a test website for a supermarket as an educational exercise with Python+Flask.我正在为超市制作一个测试网站,作为 Python+Flask 的教育练习。

When the homepage of the website is loaded I make an api call to get the top selling items in the supermarket, then I pass this information to my homepage html and render it.加载网站主页后,我调用 api 以获取超市中最畅销的商品,然后将此信息传递到我的主页 html 并渲染它。

Homepage Route主页路线

@app.route('/')
def home():
    top_items = requests.get(MY_API_URL).json()
    return render_template('home.html', top_items=top_items)

home.html主页.html

<ul id="itemList">
{% for food in top_items %}
  <li>food.name</li>  
{% endfor %}
</ul>

This works fine.这工作正常。

My api also has other endpoints that can provide information on items that are on sale and is updated regularly.我的 api 还具有其他端点,可以提供有关正在销售的物品的信息并定期更新。

Here is what I want to achieve:这是我想要实现的目标:

I want to be able to add a button to my home.html file that I can click and it can change from displaying the top selling items to the items that are on sale without reloading the page!我希望能够在我的home.html文件中添加一个按钮,我可以单击它,它可以从显示最畅销的商品更改为正在销售的商品,而无需重新加载页面!

Here is what I have done thus far:这是我到目前为止所做的:

Created a new button that will sit above my item list:创建了一个新按钮,它将位于我的项目列表上方:

<button id="saleItems">Sale Items</button>
<ul id="itemList">
{% for food in top_items %}
...

Now to write some js现在写一些js

$(document).ready(function(){
  $("#saleItems").click(function(){
    $("#itemList").//I get stuck here!
  });
});

So when the document is ready I look for the button with id saleItems to be clicked then I want to modify my list with id itemList to display only the sale items.因此,当文档准备好时,我会查找要单击的 ID 为saleItems的按钮,然后我想修改 ID 为itemList的列表以仅显示销售项目。

The problem is is that I don't know how the best way to update the list in the html.问题是我不知道如何更新 html 中的列表的最佳方法。

There are two paths I think might work:我认为有两种可能可行的途径:

1) On my home route I always make multiple requests and pass all these to the home html like so 1)在我的家庭路线上,我总是发出多个请求并将所有这些请求传递给家庭 html 就像这样

@app.route('/')
def home():
    top_items = requests.get(MY_API_URL).json()
    sale_items = requests.get(MY_API_URL_2).json()
    return render_template('home.html', top_items=top_items, sale_items=sale_items)

If I do this then I just need to figure out how to change the list from iterating over top_items to sale_items .如果我这样做,那么我只需要弄清楚如何将列表从迭代top_itemssale_items (I don't know how to do this) (我不知道该怎么做)

This doesn't seem the best practise as I will be making the 2 requests instead of 1 and that second request may never be used, for instance if the user does not press the sale items button.这似乎不是最佳实践,因为我将发出 2 个请求而不是 1 个请求,并且可能永远不会使用第二个请求,例如,如果用户没有按下销售项目按钮。

This is also not very scalable, for instance what about if I add another list for new items.这也不是很可扩展,例如,如果我为新项目添加另一个列表怎么办。

This leaves me with option这给我留下了选择

2) Somehow make the request on the button press, however I am not sure how to pass the results of this request back to html and how to tell it to render that. 2)以某种方式在按钮按下时发出请求,但是我不确定如何将此请求的结果传递回 html 以及如何告诉它渲染。

This seems better practise and more scalable.这似乎是更好的做法和更具可扩展性。

I would appreciate some help in this matter!在这件事上我会很感激一些帮助!

Thank you.谢谢你。

This is what I think could happen to keep things as DRY as possible.这就是我认为尽可能保持干燥的情况。 Please note that I haven't tested this.请注意,我没有对此进行测试。 Tell me if you have questions about any part.如果您对任何部分有疑问,请告诉我。

  1. have your different buttons for the different list item types,为不同的列表项类型设置不同的按钮,
  2. have a route return the appropriate HTML,有一条路线返回适当的 HTML,
  3. an AJAX call to get that HTML.调用 AJAX 以获取 HTML。

Item 1: buttons for each list type:第 1 项:每种列表类型的按钮:

<button id="click-btn" type="button" submiturl="/item-list/top">Top</button>
<button id="click-btn" type="button" submiturl="/item-list/sale">Sale</button>
<div id="click-response"></div><!-- placeholder for response HTML -->

Item 2: your route could look something like:第 2 项:您的路线可能类似于:

@app.route('/item-list/<item_type>', methods=('POST',))
def item_list(item_type):
    if request.method == "POST":
        items = requests.get(MY_API_URL + '/' + item_type).json()
        response = '''<ul id="itemList">'''
        for item in items:
            response += '''<li>{item.name}</li>''' 
        response += '''</ul>'''
        return response

Item 3: your AJAX call could be:第 3 项:您的 AJAX 调用可能是:

  <script>
    $(document).ready(function() {
        $("#click-btn").on('click touchstart', function() {
            $.ajax({
                url: "{{ url_for('item_list', item_type=$(this).attr('submiturl')) }}",
                method: "POST",
                success: function(response) {
                    console.log(response);
                    $('#click-response').replaceWith(response);
                },
                error: function(xhr) {
                    console.log(xhr);
                }
            });
        });
    });
  </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM