Javascript 使用CSV或JS文件在HTML表中填充特定TD
我已经四处搜索过了,但没能确定这是否可行 我开发了一个HTML页面来显示许多产品的库存状态。目前,我每天手动编辑每个状态(状态与前一天不同),并希望尽可能实现自动化 例如,我目前有一个按制造商显示的HTML页面,每个产品和库存状态显示在一个单独的表中Javascript 使用CSV或JS文件在HTML表中填充特定TD,javascript,jquery,html,csv,import,Javascript,Jquery,Html,Csv,Import,我已经四处搜索过了,但没能确定这是否可行 我开发了一个HTML页面来显示许多产品的库存状态。目前,我每天手动编辑每个状态(状态与前一天不同),并希望尽可能实现自动化 例如,我目前有一个按制造商显示的HTML页面,每个产品和库存状态显示在一个单独的表中 。折叠{ 光标:指针; 显示:块; 背景:rgb(0156,0); 颜色:rgb(255、255、255); 填充:6px 12px; 边框:纯白; } .折叠:悬停{ 颜色:rgb(231230229); 字体大小:粗体; } .折叠+输入{
。折叠{
光标:指针;
显示:块;
背景:rgb(0156,0);
颜色:rgb(255、255、255);
填充:6px 12px;
边框:纯白;
}
.折叠:悬停{
颜色:rgb(231230229);
字体大小:粗体;
}
.折叠+输入{
显示:无;
}
.折叠+输入+div{
显示:无;
}
.折叠+输入:选中+div{
显示:块;
}
宝马
产品代码
模型
库存状态
1000
M1
可用
1001
M3
缺货
1002
M5
可用
河流浅水处
产品代码
模型
库存状态
1003
嘉年华
可用
1004
蒙迪欧
可用
1004
护送
生命的终结
我将把它分解为几个单独的步骤:
1)JSON文件
如果我们仔细选择JSON文件的格式,我们可以提供构建整个页面所需的所有数据,甚至更多数据。
因此,我将把所有关于我们所有汽车的信息都放在这个文件中,这样我们就不必在添加品牌或型号后更新HTML文件
如果我们只在JSON文件中保留汽车的可用性,那么我们需要更新JSON文件和HTML文件以添加品牌或类型
可用性最好用一个整数来表示可用的汽车数量,而不是字符串。如果它是一个字符串,我们将需要解析该字符串以查看是否还有可用的汽车
通过将汽车的id与其产品代码分开,我们可以将产品代码保留为字符串,这样它就可以包含不止一个数字,并且仍然可以保持对汽车进行排序的简单方式。请记住,字符串的排序不同于整数:“10”<“9”==true
和10<9==false
。否则,如果我们有一辆代码为“999”的汽车,这可能会导致问题
另一个优点是,如果我们将其移动到数据库中,它可以很好地映射到表列
[
{
"availability": 25,
"brand": "bmw",
"code": "1000",
"id": 1,
"model": "m1"
},
{
"availability": null,
"brand": "bmw",
"code": "1001",
"id": 2,
"model": "m3"
},
{
"availability": 10,
"brand": "bmw",
"code": "1002",
"id": 3,
"model": "m5"
},
{
"availability": 7,
"brand": "ford",
"code": "1003",
"id": 4,
"model": "fiesta"
},
{
"availability": 14,
"brand": "ford",
"code": "1004",
"id": 5,
"model": "mondeo"
},
{
"availability": null,
"brand": "ford",
"code": "1005",
"id": 6,
"model": "escort"
}
]
2)获取文件
我们有两种机制来实现这一点。如果必须与旧浏览器兼容,可以使用旧的XMLHttpRequest()
。或者新浏览器的fetch()
API。
这个选择将决定我们是否必须使用回调或承诺。(除非我们也将XMLHttpRequest版本转换为承诺。)
XMLHttpRequest:
// The path where we can find the JSON file.
const PATH_CARS = 'http://path/to/cars.json';
// A getJSON function that will create an ajax request to the provided URL.
const getJSON = ( url, callback ) => {
// Create a new XMLHttpRequest.
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
const request = new XMLHttpRequest();
// Open the request before setting other properties. ( IE11 )
request.open( 'GET', url );
// When the request gets the file, we want to run the callback.
// The responseText will be the JSON string inside our json file.
request.onload = function() {
callback( request.responseText );
};
request.send();
};
// Use the function to get the file.
// Parse and log the contents of the file once it arrives.
getJSON( PATH_CARS, function( response ) {
// cars will be a string here. We want the actual JS object represented by the JSON string
const cars = JSON.parse( response );
console.log( cars );
});
获取:
// The path where we can find the JSON file.
const PATH_CARS = 'http://path/to/cars.json';
// Same thing, but using the fetch API for browsers that support it.
// https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
// The fetch API uses promises instead of callbacks to handle the results.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
fetch( PATH_CARS )
.then( response => response.json())
.then( cars => {
console.log( cars );
});
3)创建表格
我们将稍微改变一下逻辑。我们不需要使用来自文件的值更新固定的HTML,而只需要从JSON文件创建整个表,以便所有更新都已在表中
如果我们需要再次更新该表,我们可以重新提交整个表,而不是尝试将HTML节点与JSON中的正确值匹配。对于大量的汽车来说,这不会太快,但仍然比单独更新每辆汽车快得多
这属于我们所称的模型-视图-控制器体系结构。JSON文件为我们提供了一个汽车模型。HTML表是该模型的一个视图。javascript代码将其作为控制器绑定在一起。控制器获取模型,并将模型转换为表示该模型的视图。每次模型更改时(您向JSON文件添加一辆汽车),我们都可以请求控制器获取更新的模型(加载JSON文件)并更新视图。(再次渲染表格)
//我们需要为每个品牌创建一个表。
//我们需要为该类型的每个车型创建一个表行。
//对于大型项目,可以使用模板语言来创建HTML。
//对于像thing这样小的东西,我们可以求助于简单的字符串操作。
const createTables=品牌=>{
//循环所有品牌,为每个品牌创建一个表格。
//这次我将使用reduce,以显示reduce()和我们在上一步中使用的forEach()之间的区别和相似性。
const tables=brands.reduce((html,brand)=>{
//复制标题,替换品牌名称。
const header=`${brand.name}产品代码:型号:库存:`;
//在车辆上循环并为每辆车创建一行。
//由于我们创建的行数与数组中的汽车数相同,因此我们可以
// We need to create a table for each brand.
// We need to create a table row for each car model of that type.
// For big projects, one would use a templating language to create the HTML.
// For something as small as thing, we can resort to simple string manipulation.
const createTables = brands => {
// Loop over all the brands, creating a table for each brand.
// I'll use a reduction this time, to show the difference and similarities between reduce() and the forEach() we used in the previous step.
const tables = brands.reduce(( html, brand ) => {
// Copy the header, replacing the brand name.
const header = `<table><thead><tr><th colspan="3">${ brand.name }</th></tr><tr><th>Product Code:</th><th>Model:</th><th>In Stock:</th></tr></thead><tbody>`;
// Loop over the cars and create a row for each car.
// Since we create the same amount of rows as we have cars inside the array, we can use .map()
const rows = brand.cars.map( car => {
// Since we changed the availability to a number, we hve to recreate the string for it.
// This allows us to easily change the label without having to change the logic in multiple places
const availability_label = Number.isInteger( car.availability )
? `${ car.availability } in stock.`
: 'End of life.';
return `<tr><td>${ car.code }</td><td>${ car.model }</td><td>${ availability_label }</td></tr>`;
});
// Append the current header, car rows and the closing tags to the previous HTML, then return.
return html += `${ header }${ rows.join('') }</tbody></table>`;
}, '');
// Return the HTML string. We could also just return the reduction directly, wihtout using th tables variable in between.
return tables;
};