将JSON数据放入表格的问题: – Flask JavaScript jQuery 将JSON数据放入表格中?

huangapple go评论60阅读模式
英文:

Flask Javascript Jquery Put Json data into Table?

问题

Here is the translated content from your provided code:

所以我正在运行Flask。到目前为止,我已经能够使用Javascript获取我的Python脚本的输出(以JSON格式返回库存和价格)。

现在我正在尝试使用jQuery将这个JSON数据转换成HTML表格。不幸的是,我对Javascript不是很擅长。通常情况下,我喜欢尽可能多地在Python中完成工作,但我需要一些帮助来实现结果。

价格端点返回的JSON如下所示:

[{ '0.1': '1387' }, { '0.1': '6060' }, { '0.2': '7000' }]

最终结果,我想要将这些信息显示在一个带有jQuery的表格中,所以只有在我们有数据后表格才会显示。另外,对于重复的价格,我想要将库存相加,如下所示:

价格 | 库存
0.1   | 7447
0.2   | 7000

我的代码:

{% extends "_base.html" %}
{% block content %}
{% if current_user.is_authenticated %}
<h3 class="text-center">欢迎 {{current_user.email}}! {{current_user.balance}}</h3>
{% else %}
<h3 class="text-center">价格列表</h3>
{% endif %}
<br>
<div class="form-group">
  <form action="" method="post">
  <div class="input-group mb-3-center" style="display: flex;justify-content: center;">
      <div class="input-group-prepend">
      <label for="inputsm">国家</label>
      <br>
      <select class="selectpicker" data-live-search="true" id="country" onchange="update()">
        <option value="select">选择一个国家...</option>
        <option value="1">一个</option>
        <option value="2">二</option>
        <option value="3">三</option>
      </select>
      <br>
      <br>
      <label for="inputsm">服务</label>
      <br>
      <select class="selectpicker" data-live-search="true" id="service" onchange="update()">
        <option value="select">选择一个服务...</option>
        <option value="1">一个</option>
        <option value="2">二</option>
        <option value="3">三</option>
      </select>
      <br>
      <br>
      <label for="inputsm">价格</label>
      <span class="input-group-text" style="font-size: medium;">$</span>
      <br>
      <label for="inputsm">库存</label>
      <span class="input-group-text" style="font-size: medium;">-</span>
      <br>
    </div>
  </div>
  </form>
  </div>
  <div id="table">
    <table>
        <tbody>
            <th>价格</th>
            <th>库存</th>
        </tbody>
    </table>
</div>
  <script>
    function update() {
    const countrySelect = document.getElementById('country').value;
    const serviceSelect = document.getElementById('service').value;
    if (countrySelect != 'select' && serviceSelect != 'select') {
      async function logJSONData(service, country) {
          const settings = {
              method: 'POST',
              headers: {
                  'Content-Type': 'application/json',
              }
          };
          const response = await fetch("http://localhost/prices?service=" + service + "&country=" + country, settings);
          const jsonData = await response.json();
          console.log(jsonData);
      }
      logJSONData(serviceSelect, countrySelect);
      
      $(table).find('tbody').append("<tr><td>jsonData</td></tr>");
    }
  }
    </script>
{% endblock %}

Please note that the code you provided contains some HTML, JavaScript, and template syntax. If you have any specific questions or need further assistance with this code, please let me know.

英文:

so I am running Flask. And I have been able to so far grab the output of my python script (which returns the stock and prices available in json format) with Javascript.

Now I am trying to convert this json data into a html table using jquery. Unfortunately, I'm not the best with Javascript. I typically like to do as much as I can in Python, but I'm needing some help to achieve the result.

The prices endpoint returns json like so:

[{&#39;0.1&#39;: &#39;1387&#39;}, {&#39;0.1&#39;: &#39;6060&#39;}, {&#39;0.2&#39;: &#39;7000&#39;]}

For the end result, I would like to display this information into a table with jquery, so the table only appears after we have data. Also for duplicate prices I would like to add the stock together like so:

Price | Stock
0.1   | 7447
0.2   | 7000

My code:

{% extends &quot;_base.html&quot; %}
{% block content %}
{% if current_user.is_authenticated %}
&lt;h3 class=&quot;text-center&quot;&gt;Welcome {{current_user.email}}! {{current_user.balance}}&lt;/h3&gt;
{% else %}
&lt;h3 class=&quot;text-center&quot;&gt;Price List&lt;/h3&gt;
{% endif %}
&lt;br&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;form action=&quot;&quot; method=&quot;post&quot;&gt;
&lt;div class=&quot;input-group mb-3-center&quot; style=&quot;display: flex;justify-content: center;&quot;&gt;
&lt;div class=&quot;input-group-prepend&quot;&gt;
&lt;label for=&quot;inputsm&quot;&gt;Country&lt;/label&gt;
&lt;br&gt;
&lt;select class=&quot;selectpicker&quot; data-live-search=&quot;true&quot; id=&quot;country&quot; onchange=&quot;update()&quot;&gt;
&lt;option value=&quot;select&quot;&gt;Select a country...&lt;/option&gt;
&lt;option value=&quot;1&quot;&gt;One&lt;/option&gt;
&lt;option value=&quot;2&quot;&gt;Two&lt;/option&gt;
&lt;option value=&quot;3&quot;&gt;Three&lt;/option&gt;
&lt;/select&gt;
&lt;br&gt;
&lt;br&gt;
&lt;label for=&quot;inputsm&quot;&gt;Service&lt;/label&gt;
&lt;br&gt;
&lt;select class=&quot;selectpicker&quot; data-live-search=&quot;true&quot; id=&quot;service&quot; onchange=&quot;update()&quot;&gt;
&lt;option value=&quot;select&quot;&gt;Select a service...&lt;/option&gt;
&lt;option value=&quot;1&quot;&gt;One&lt;/option&gt;
&lt;option value=&quot;2&quot;&gt;Two&lt;/option&gt;
&lt;option value=&quot;3&quot;&gt;Three&lt;/option&gt;
&lt;/select&gt;
&lt;br&gt;
&lt;br&gt;
&lt;label for=&quot;inputsm&quot;&gt;Price&lt;/label&gt;
&lt;span class=&quot;input-group-text&quot; style=&quot;font-size: medium;&quot;&gt;$&lt;/span&gt;
&lt;br&gt;
&lt;label for=&quot;inputsm&quot;&gt;Stock&lt;/label&gt;
&lt;span class=&quot;input-group-text&quot; style=&quot;font-size: medium;&quot;&gt;-&lt;/span&gt;
&lt;br&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;div id=&quot;table&quot;&gt;
&lt;table&gt;
&lt;tbody&gt;
&lt;th&gt;Price&lt;/th&gt;
&lt;th&gt;Stock&lt;/th&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;script&gt;
function update() {
const countrySelect = document.getElementById(&#39;country&#39;).value;
const serviceSelect = document.getElementById(&#39;service&#39;).value;
if (countrySelect != &#39;select&#39; &amp;&amp; serviceSelect != &#39;select&#39;) {
async function logJSONData(service,country) {
const settings = {
method: &#39;POST&#39;,
headers: {
&#39;Content-Type&#39;: &#39;application/json&#39;,
}
};
const response = await fetch(&quot;http://localhost/prices?service=&quot;+service+&quot;&amp;country=&quot;+country, settings);
const jsonData = await response.json();
console.log(jsonData);
}
logJSONData(serviceSelect,countrySelect);
$(table).find(&#39;tbody&#39;).append(&quot;&lt;tr&gt;&lt;td&gt;jsonData&lt;/td&gt;&lt;/tr&gt;&quot;);
}
}
&lt;/script&gt;
{% endblock %}

答案1

得分: 0

要在HTML表格中使用jQuery显示JSON数据,以达到您期望的结果,您可以使用以下方法:

在您的HTML文件中添加一个空的<table>元素,该元素将用于显示表格:

<table id="priceTable">
  <thead>
    <tr>
      <th>价格</th>
      <th>库存</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

现在,您可以使用jQuery来获取JSON数据并动态填充表格。在一个<script>标签中添加以下JavaScript代码:

<script>
$(document).ready(function() {
// 使用jQuery的AJAX方法获取JSON数据
$.ajax({
url: '/prices', // 用您的Flask端点的适当URL替换此处
method: 'GET',
dataType: 'json',
success: function(data) {
// 处理接收到的JSON数据并填充表格
var tableBody = $('#priceTable tbody');
var prices = {};
// 计算每个唯一价格的总库存
data.forEach(function(item) {
var price = Object.keys(item)[0];
var stock = parseInt(item[price]);
if (prices.hasOwnProperty(price)) {
prices[price] += stock;
} else {
prices[price] = stock;
}
});
// 使用计算出的价格和库存填充表格
Object.keys(prices).forEach(function(price) {
var stock = prices[price];
var row = '<tr><td>' + price + '</td><td>' + stock + '</td></tr>';
tableBody.append(row);
});
},
error: function() {
console.error('获取价格数据失败。');
}
});
});
</script>

确保在AJAX URL中将'/prices'替换为与返回JSON数据的Flask端点相对应的适当URL。

使用此代码,当页面加载时,jQuery脚本将从指定的URL获取JSON数据。然后,它将计算每个唯一价格的总库存,并相应地填充<table>中的价格和库存。

注意:确保Flask端点/prices以与您的示例中所示的正确格式返回JSON数据。

英文:

To achieve your desired result of displaying the JSON data in an HTML table using jQuery, you can use the following approach:

Add an empty &lt;table&gt; element to your HTML file where you want the table to appear:

&lt;table id=&quot;priceTable&quot;&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;Price&lt;/th&gt;
      &lt;th&gt;Stock&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

Now, you can use jQuery to fetch the JSON data and populate the table dynamically. Add the following JavaScript code inside a &lt;script&gt; tag:

&lt;script&gt;
$(document).ready(function() {
// Fetch the JSON data using jQuery&#39;s AJAX method
$.ajax({
url: &#39;/prices&#39;, // Replace with the appropriate URL for your Flask endpoint
method: &#39;GET&#39;,
dataType: &#39;json&#39;,
success: function(data) {
// Process the received JSON data and populate the table
var tableBody = $(&#39;#priceTable tbody&#39;);
var prices = {};
// Calculate the total stock for each unique price
data.forEach(function(item) {
var price = Object.keys(item)[0];
var stock = parseInt(item[price]);
if (prices.hasOwnProperty(price)) {
prices[price] += stock;
} else {
prices[price] = stock;
}
});
// Populate the table with the calculated prices and stocks
Object.keys(prices).forEach(function(price) {
var stock = prices[price];
var row = &#39;&lt;tr&gt;&lt;td&gt;&#39; + price + &#39;&lt;/td&gt;&lt;td&gt;&#39; + stock + &#39;&lt;/td&gt;&lt;/tr&gt;&#39;;
tableBody.append(row);
});
},
error: function() {
console.error(&#39;Failed to fetch price data.&#39;);
}
});
});
&lt;/script&gt;

Make sure to replace &#39;/prices&#39; in the AJAX URL with the appropriate URL that corresponds to your Flask endpoint that returns the JSON data.

With this code, when the page loads, the jQuery script will fetch the JSON data from the specified URL. It will then calculate the total stock for each unique price and populate the &lt;table&gt; with the prices and stocks accordingly.

> Note: Ensure that the Flask endpoint /prices returns the JSON data in the correct format as shown in your example.

huangapple
  • 本文由 发表于 2023年6月13日 07:20:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76460833.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定