[英]How to fetch data from json file and display in html?
我有一个 JSON 数据库,如果找到数组中的特定元素,我想在我的 JavaScript/HTML 中自动填充这些信息。 我有一个处理程序事件,onchange 监听是否找到该特定元素,它会打印该特定数组的所有信息。 我已将它打印到控制台中,但我 go 如何将其打印到我的相关 HTML 部分?
JavaScript:
const getAssetInfo = id => {
$.get( "http://localhost:3000/assets/" + id, function( data ) {
console.log(data);
});
}
$('document').ready(() => {
<td><input id='asset_tag_no${count}' type='text' onchange = "getAssetInfo(this.value);" bottom required /></td>
<td><input id='manufacturer_serial_no${count}' type='text' bottom required/></td>
<td><textarea id='description${count}' type='text' bottom required description></textarea></td>
}
let data = [];
// Store all Info from this row
let assetInfo = {
asset_tag_no: $(`#asset_tag_no${i}`).val(),
manufacturer: $(`#manufacturer_serial_no${i}`).val(),
descriptions: $(`#description${i}`).val(),
costs: $(`#cost${i}`).val(),
po_no: $(`#po_no${i}`).val(),
remarks: $(`#remarks${i}`).val(),
}
}
JSON 在数据库中
{
"assets" : [
{
"id": "0946",
"description" : "SONY - Camera",
"manufacturer" : "SONY",
}
}
控制台返回数据的屏幕截图和所需输入人口的示例:
所以我认为你可以这样做:
假设您是 html 表的结构如下所示:
<tr>
<td><input class="asset-tag" id='asset_tag_no${count}' type='text' onchange="getAssetInfo(this)" bottom required /></td>
<td><input class="serial-no" id='manufacturer_serial_no${count}' type='text' bottom required/></td>
<td><textarea class="description" id='description${count}' type='text' bottom required description></textarea></td>
</tr>
请注意,我已将class
属性添加到我们稍后将使用的每个输入。 此外,我将 onChange 更新为getAssetInfo(this)
,它将传递实际的输入元素本身(而不仅仅是值)。
有了这个,你可以有一个像这样的getAssetInfo
function
const getAssetInfo = (inputElement) => {
// get the asset tag id
const id = $(inputElement).val();
// get the table row that this input is in
const row = $(inputElement).closest("tr");
$.get(id, (data) => {
// find the `.description` element and set it's value
$(row).find("textarea.description").val(data.description);
// find the `.serial-no` element and set it's value
$(row).find("input.serial-no").val(data.manufacturer);
// ... add more finders and setters based on whatever else you're getting back from the data.
});
};
一旦这一切都设置好了,我想你会发现它是有效的。 我没有添加您在示例中显示的所有输入元素,但希望您能弄清楚如何将其扩展到您的需要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.