试图使用AJAXFlask从API更新价格。

问题描述 投票:1回答:1

所以我想更新产品的价格,而不需要刷新。我希望它能实时更新,但我不明白。我看了很多帖子,但都没有弄明白。

这是我的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个回答
0
投票

要显示 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>

输出。

live data using flask and ajax

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

© www.soinside.com 2019 - 2024. All rights reserved.