You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Axios接口请求结果嵌入HTML表格?是否可无需依赖本地JSON文件完成数据传递?

Absolutely! You can totally skip the hassle of copying local JSON files by fetching the API data directly in the browser and rendering it into an HTML table on the fly. Here's a complete, working solution tailored to your needs:

Full HTML File Example

This code combines the API request, data handling, and table rendering all in one file—no extra steps needed:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ADA/LCX Order Book</title>
    <style>
        table {
            border-collapse: collapse;
            width: 80%;
            margin: 20px auto;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: right;
        }
        th {
            background-color: #f2f2f2;
        }
        .order-book-container {
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="order-book-container">
        <h1>ADA/LCX Order Book</h1>
        <div id="table-container"></div>
    </div>

    <script>
        // Fetch order book data and render the table when the page loads
        async function fetchAndRenderOrderBook() {
            try {
                // Make the POST request directly to LCX's API
                const response = await fetch('https://exchange-api.lcx.com/order/book', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ pair: 'ADA/LCX' })
                });

                if (!response.ok) {
                    throw new Error(`Request failed with status: ${response.status}`);
                }

                const orderBookData = await response.json();
                renderOrderBookTable(orderBookData);
            } catch (error) {
                console.error('Error loading order book:', error);
                document.getElementById('table-container').innerHTML = `<p>Oops, failed to load order book data. Try again later!</p>`;
            }
        }

        // Convert the JSON data into HTML tables
        function renderOrderBookTable(data) {
            const container = document.getElementById('table-container');
            
            // Handle cases where bids/asks might be missing
            if (!data.bids || !data.asks) {
                container.innerHTML = `<p>No order book data available right now.</p>`;
                return;
            }

            // Create separate tables for bids (buy orders) and asks (sell orders)
            container.innerHTML = `
                <h2>Bids (Buy Orders)</h2>
                ${createOrderTable(data.bids)}
                <h2>Asks (Sell Orders)</h2>
                ${createOrderTable(data.asks)}
            `;
        }

        // Helper to build a table from order data
        function createOrderTable(orders) {
            if (orders.length === 0) {
                return `<p>No orders listed here.</p>`;
            }

            // Assuming each order is an array with [price, quantity] (matches common order book structures)
            let tableHTML = `
                <table>
                    <thead>
                        <tr>
                            <th>Price</th>
                            <th>Quantity</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            orders.forEach(order => {
                tableHTML += `
                    <tr>
                        <td>${order[0]}</td>
                        <td>${order[1]}</td>
                    </tr>
                `;
            });

            tableHTML += `
                    </tbody>
                </table>
            `;
            return tableHTML;
        }

        // Run the function as soon as the page finishes loading
        window.addEventListener('load', fetchAndRenderOrderBook);
    </script>
</body>
</html>

Key Details

  • No local JSON needed: The fetch API makes the POST request directly to LCX's endpoint, so you skip saving and copying files entirely.
  • Error handling: If the API call fails (e.g., network issues, invalid response), the page shows a user-friendly message instead of breaking.
  • Clean rendering: The code splits bids and asks into separate tables for readability, with basic styling to make the data easy to scan.

If You Prefer Using Axios

If you want to stick with Axios (like your original Node.js code), just add the Axios CDN to the <head> section and adjust the request code:

<!-- Add this to your <head> -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Then update the fetchAndRenderOrderBook function:

async function fetchAndRenderOrderBook() {
    try {
        const response = await axios.post('https://exchange-api.lcx.com/order/book', {
            pair: 'ADA/LCX'
        }, {
            headers: { 'Content-Type': 'application/json' }
        });

        renderOrderBookTable(response.data);
    } catch (error) {
        console.error('Error loading order book:', error);
        document.getElementById('table-container').innerHTML = `<p>Oops, failed to load order book data. Try again later!</p>`;
    }
}

Quick Note on CORS

If you run into a "CORS policy" error in the browser, that means LCX's API doesn't allow direct requests from frontend code. In that case, you can set up a simple Node.js proxy server to forward the request (just modify your original code to act as a middleman and serve the data to your HTML page).

内容的提问来源于stack exchange,提问作者Iulian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 11:57:49