【问题标题】:Trying to update prices from an API using AJAX/Flask尝试使用 AJAX/Flask 从 API 更新价格
【发布时间】:2020-06-02 15:41:43
【问题描述】:

所以我正在尝试更新产品的价格,而无需刷新。等它更新直播,但我不明白。看了一堆帖子,没搞明白。

这是我的python代码:

@app.route('/bprices', methods=['GET'])
def bPrices():
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=[can get you a key if needed]').json()

    products = [
        {
            "id": product["product_id"],
            "sell_price": product["sell_summary"][:1],
            "buy_price": product["buy_summary"][:1],
            "sell_volume": product["quick_status"]["sellVolume"],
            "buy_volume": product["quick_status"]["buyVolume"],
        }
        for product in f["products"].values()
    ]
    return jsonify(products=products)

这是我的 HTML + js:

<table
    id="myTable"
    class="table table-striped table-bordered table-sm table-dark sortable"
    cellspacing="0"
  >
    <thead>
      <tr>
        <th aria-label="Product Name" data-balloon-pos="up">Product</th>
        <th aria-label="Product's buy price" data-balloon-pos="up">
          Buy Price
        </th>
        <th aria-label="Product's sell price" data-balloon-pos="up">
          Sell Price
        </th>
        <th aria-label="Product's buy volume" data-balloon-pos="up">
          Buy Volume
        </th>
        <th aria-label="Product's sell volume" data-balloon-pos="up">
          Sell Volume
        </th>
        <th>
          Margin
        </th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td id="price"></td>
      </tr>
    </tbody>
  </table>
</div>
<script>
  $SCRIPT_ROOT = {{ request.script_root | tojson | safe }};
    (function () {
      $.getJSON(
        $SCRIPT_ROOT + "/_stuff", // Your AJAX route here
        function (data) {
          $("#price").text(data.products)
        }
      );
      setTimeout(arguments.callee, 10000);
    })();
</script>

目前,它只显示我想要访问的数据的 JSON 文件,很可能是因为“jsonify”。

【问题讨论】:

    标签: python ajax flask


    【解决方案1】:

    要在表格视图中显示 JSON 数据,请在 jquery 中循环遍历产品并在 tbody 元素内创建表格记录。然后将此tbody 插入所需的表中。

    这里我展示了一个使用 AJAX 和 Flask 在不刷新页面的情况下显示实时数据的示例。

    app.py:

    from random import randint
    from flask import Flask, render_template, jsonify, request
    
    
    
    app = Flask(__name__)
    
    
    @app.route("/get_data", methods=["GET"])
    def get_data():
        products = [
            {
                "name": "mobile",
                "quantity": 3217210,
                "price": randint(1,1000)
            },
            {
                "name": "laptop",
                "quantity": 343217210,
                "price": randint(1,1000)
            },
            {
                "name": "mouse",
                "quantity": 100,
                "price": randint(1,1000)
            }        
        ]
        return jsonify(products=products)
    
    
    
    @app.route("/", methods=["GET"])
    def home():
        return render_template("products.html")
    

    products.html:

    <!DOCTYPE html>
    <html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
        <title>Live Prices</title>
    </head>
    <body>
        <h3>Products</h3>
        <table border="1" id="products_table">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Quantity</th>
                    <th>Price</th>
                </tr>
            </thead>
        </table>
        <script type=text/javascript>
            $SCRIPT_ROOT = {{ request.script_root | tojson | safe }};
            (function () {
                $.getJSON($SCRIPT_ROOT + "/get_data",
                function(data) {
                    var products = data.products;
                    var table_body = document.createElement("tbody");
                    $.each(products, function(index, product){
                        var product_name = product.name.toString();
                        var product_quantity = product.quantity;
                        var product_price = product.price;
                        var row = table_body.insertRow();
                        var name_cell = row.insertCell();
                        name_cell.appendChild(document.createTextNode(product_name));
                        var quantity_cell = row.insertCell();
                        quantity_cell.appendChild(document.createTextNode(product_quantity));
                        var price_cell = row.insertCell();
                        price_cell.appendChild(document.createTextNode(product_price));
                    })
                    $("#products_table tbody").remove();
                    $("#products_table").append(table_body);
                }
                );
                setTimeout(arguments.callee, 5000);
            })();
        </script>
    </body>
    </html>
    

    输出:

    注意: - 在get_data 路由中,我为每个GET 请求中的每个产品生成了1 到1000 之间的随机价格。 - 在setTimeout(arguments.callee, 5000); 中,5000 表示它将在脚本执行之间延迟 5000 毫秒(=5 秒)。

    【讨论】:

    • 不,我并没有真正让它工作,我仍然对我浏览器上的 JSON 页面感到厌烦。
    • 你试过运行我的例子吗?如果你成功了,你可以在你自己的代码中实现它。
    • 是的,我试过你的。我认为这与我的 jquery 脚本有关。我之前在 Jquery 无法工作时遇到过问题,即使它已安装。我会尝试一些事情。
    • hmm 我尝试手动安装 jquery,但在那部分没有运气。我只是得到产品的 JSON。
    • 哦!发现了问题。我的 .py 文件中没有“家”或“/”路线。让我们试着把我的东西放在那里哈哈,谢谢你的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    • 2012-07-22
    • 2017-05-02
    • 2022-10-21
    • 1970-01-01
    • 2020-12-23
    相关资源
    最近更新 更多