簡體   English   中英

使用CSV或JS文件在HTML表中填充特定的TD

[英]Using a CSV or JS file to populate specific TD in HTML table

我已經搜索了一下,但無法查看是否可行。

我已經開發了一個HTML頁面來顯示許多產品的庫存狀態。 我目前每天都在手動編輯每個狀態(狀態與前一天相比有所更改),並且希望在可能的情況下自動進行。

例如,我目前有按制造商顯示的HTML頁面,每個產品和庫存狀態都在單獨的表格中。

 .collapse{ cursor: pointer; display: block; background: rgb(0, 156, 0); color: rgb(255, 255, 255); padding: 6px 12px; border: solid white; } .collapse:hover{ color: rgb(231, 230, 229); font-weight: bold; } .collapse + input{ display: none; } .collapse + input + div{ display:none; } .collapse + input:checked + div{ display:block; } 
 <body> <div><label class="collapse" for="_bmw">BMW</label> <input id="_bmw" type="checkbox"> <div><br> <table border="1" cellpadding="1" cellspacing="1"> <thead> <tr style="font-weight: bold"> <td style="width: 75px;">Product Code</td> <td style="width: 200px;">Model</td> <td style="width: 200px;">Stock Status</td> </tr> </thead> <tbody> <tr> <td>1000</td> <td>M1</td> <td>Available</td> </tr> <tr> <td>1001</td> <td>M3</td> <td>Out of stock</td> </tr> <tr> <td>1002</td> <td>M5</td> <td>Available</td> </tr> </tbody> </table> <br> </div> </div> <div><label class="collapse" for="_ford" style="font-size: 17px;">Ford</label> <input id="_ford" type="checkbox"> <div><br> <table border="1" cellpadding="1" cellspacing="1"> <thead> <tr style="font-weight: bold"> <td style="width: 75px;">Product Code</td> <td style="width: 200px;">Model</td> <td style="width: 200px;">Stock Status</td> </tr> </thead> <tbody> <tr> <td>1003</td> <td>Fiesta</td> <td>Available</td> </tr> <tr> <td>1004</td> <td>Mondeo</td> <td>Available</td> </tr> <tr> <td>1004</td> <td>Escort</td> <td>End of life</td> </tr> </tbody> </table> <br> </div> </div> </body> 

是否可以使用javascript或jquery在HTML表中執行產品代碼查找,並從“庫存狀態TD”中的JS(或CSV)文件返回值?

我已經使用以下數據創建了一個JS文件,現在我只需要知道如何基於對產品代碼的查找來填充庫存狀態數據:-

 [ { "FIELD1": "1000", "FIELD2": "Available" }, { "FIELD1": "1001", "FIELD2": "Out of stock" }, { "FIELD1": "1002", "FIELD2": "Available" }, { "FIELD1": "1003", "FIELD2": "Available" }, { "FIELD1": "1004", "FIELD2": "Available" }, { "FIELD1": "1005", "FIELD2": "End of life" }, ] 

我是JS&JQuery的新手,因此非常感謝您的幫助。 如果我錯過了任何事情,或者您需要進一步的信息,請詢問。

我將其分解為單獨的步驟:

1)JSON文件

如果我們仔細選擇JSON文件的格式,則可以提供所有數據,甚至還可以提供構造整個頁面所需的數據。 因此,我會將與我們擁有的所有汽車有關的所有信息都放在此文件中,因此我們不必在添加品牌或型號后更新HTML文件。

如果僅在JSON文件中保留汽車的可用性,則需要同時更新JSON文件和HTML文件以添加品牌或類型。

可用性也更好地表示為代表可用的汽車數量的整數,而不是字符串。 如果是字符串,我們將需要解析該字符串以查看是否還有可用的汽車。

通過將汽車ID與產品代碼分開,我們可以將產品代碼保留為字符串,這樣它不僅可以包含數字,還可以保持一種簡單的方式對我們的汽車進行排序。 請記住,字符串的排序方式不同於整數: "10" < "9" === true10 < 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。 這個選擇將決定我們是否必須使用回調或Promise。 (除非我們也將XMLHttpRequest版本也轉換為promise。)

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中的正確值進行匹配。 對於大量的汽車來說,這不會那么快(想想1000輛以上),但是比單獨更新每輛汽車要快得多。

這屬於我們所謂的“模型-視圖-控制器”架構。 JSON文件為我們提供了汽車模型。 HTML表是該模型的視圖。 javascript代碼將其全部綁定為控制器。 控制器獲取模型,然后將模型轉換為代表該模型的視圖。 每次模型更改時(將汽車添加到JSON文件),我們都可以請求控制器獲取更新的模型(加載JSON文件)並更新視圖。 (再次渲染表格)

//  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;
};

4)放在一起

使用示例中創建的所有技術和功能,我們現在擁有了創建整個應用程序的一切。 我添加了另一個幫助程序功能,可將所有汽車分組到各自的品牌中,因此創建表變得更加容易和清晰。

我在下面的示例中模擬了JSON文件的提取,因此我們可以實際運行代碼。 在您自己的代碼中,您將使用實際的fetch()或XMLHttpRequest()代碼。

 // FAKE FETCH, DO NOT USE IN THE REAL CODE const fetch = url => Promise.resolve({json: () => JSON.parse('[{"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"}]')}); // 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 const getCars = url => fetch( url ) .then( response => response.json()) .catch( error => console.error( error )); // We need to group all the different cars into their respective brands. const groupBrands = cars => { // Create a temporary object we'll use to store the different brands. const brands = {}; // Loop over all the car models, grouping them into the correct brand. cars.forEach( car => { // Extract the brand name from the car item. const brand = car.brand; // If we haven't seen this brand yet, add it to the different brands as an array. if ( !brands.hasOwnProperty( brand )) brands[ brand ] = []; // Push the car model to the brand. brands[ brand ].push( car ); }); // We now have an object containign all the cars grouped by brand. // It would be easier however, if we had ana rray we can loop over easily. // So transform the object back into an array. // We loop over the entries array of the object to extarct the name and cars at the same time, then wrap them back into an object. return Object.entries( brands ).map(([ name, cars ]) => ({ name, cars })); // This entire step can be done in one expression by using array.reduce() instead of array.forEach() // We could also just return the object and loop over the entries in the render function. // My personal preference is to always use an array to represent multiples of something: // A 'collection' of 'brand' objects with each brand containing a 'collection' of 'car' objects. // We could also already do this grouping inside the JSON file itsself, but I preferred to keep the JSON file itsself simple for this example. }; // 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; }; // We have a JSON file, we can fetch that file, we can create tables from the contents, time to put it all together. // Fetch the JSON file. getCars( PATH_CARS ) // Group the cars into brands. .then( groupBrands ) // Create a table for each group. .then( createTables ) // Render the tables into the page. .then( html => { const tableHook = document.querySelector( '#cars' ); if ( tableHook ) tableHook.innerHTML = html; // else throw new Error(); something went wrong. }) // Catch any errors encountered. .catch( error => console.error( error )); 
 <html> <head> <title>Car Stocks</title> </head> <body> <div id="cars"></div> </body> </html> 

5)升級

上面的許多代碼都可以寫得更短一些,但是我故意使用更長的版本,以將要學習的新知識數量降至最低。 在不支持promise的情況下,可以使用回調編寫相同的代碼。 在內部,功能基本上保持不變。

我會再給您重新添加CSS,因為這樣做已經很好了。

我已經實現了以下代碼,該代碼可用於我從日常庫存報告中導出的JSON數據。

 $(document).ready( function() { $.ajax({ url: "data.json", method: "GET", dataType: "json", success: function(data) { var $tbody = $("table#data tbody"); $.each(data, function(i, data) { var $tr = $("<tr></tr>"); $tr.appendTo($tbody); var $td = $("<td></td>"); $td.html(data.ProdCode) .appendTo($tr); $td = $("<td></td>"); $td.html(data.Model) .appendTo($tr); $td = $("<td></td>"); $td.html(data.StockStatus) .appendTo($tr); }); }, error: function(jqXHR, textStatus, errorThrown) { console.log("AJAX ERROR",textStatus,errorThrown,jqXHR); } }); }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM