英文:
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:
[{'0.1': '1387'}, {'0.1': '6060'}, {'0.2': '7000']}
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 "_base.html" %}
{% block content %}
{% if current_user.is_authenticated %}
<h3 class="text-center">Welcome {{current_user.email}}! {{current_user.balance}}</h3>
{% else %}
<h3 class="text-center">Price List</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">Country</label>
<br>
<select class="selectpicker" data-live-search="true" id="country" onchange="update()">
<option value="select">Select a country...</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<br>
<br>
<label for="inputsm">Service</label>
<br>
<select class="selectpicker" data-live-search="true" id="service" onchange="update()">
<option value="select">Select a service...</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<br>
<br>
<label for="inputsm">Price</label>
<span class="input-group-text" style="font-size: medium;">$</span>
<br>
<label for="inputsm">Stock</label>
<span class="input-group-text" style="font-size: medium;">-</span>
<br>
</div>
</div>
</form>
</div>
<div id="table">
<table>
<tbody>
<th>Price</th>
<th>Stock</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 %}
答案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 <table>
element to your HTML file where you want the table to appear:
<table id="priceTable">
<thead>
<tr>
<th>Price</th>
<th>Stock</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Now, you can use jQuery to fetch the JSON data and populate the table dynamically. Add the following JavaScript code inside a <script>
tag:
<script>
$(document).ready(function() {
// Fetch the JSON data using jQuery's AJAX method
$.ajax({
url: '/prices', // Replace with the appropriate URL for your Flask endpoint
method: 'GET',
dataType: 'json',
success: function(data) {
// Process the received JSON data and populate the table
var tableBody = $('#priceTable tbody');
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 = '<tr><td>' + price + '</td><td>' + stock + '</td></tr>';
tableBody.append(row);
});
},
error: function() {
console.error('Failed to fetch price data.');
}
});
});
</script>
Make sure to replace '/prices'
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 <table>
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论