fara
10 ماه پیش توسط fara مطرح شد
0 پاسخ

مشکل در کد گرفتن API

یک وب پیج درست کردم که از یک لینک دارای ۱۰۰۰ و خورده ای API اون هارو بگیره و ۵۰ تا ۵۰ تا در یک جدول نشون بده و بعد از هر رفرش ۵۰ تای بعدی رو نشون بده و میخام براساس category فیلتر بشه اما فیلترم کار نمیکنه.
کد html:


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>API table</title>
</head>
<body>
    <div id="filter-container">
        <label for="category-filter">Categories:</label>
        <select id="category-filter">
            <option value="all">All</option>
            <!-- Add other category options here -->
        </select>
        <button id="filter-button">Filter</button>
        <button id="refresh-button">Refresh</button>
    </div>
    <table id="api-table">
        <thead id="table-head"></thead>
        <tbody id="api-list"></tbody>
    </table>
    <script src="script.js"></script>
</body>
</html>

کد css:

body {
    margin: 0;
    padding: 0;
}

#filter-container {
    position: sticky;
    top: 0;
    background-color: #f1f1f1;
    padding: 10px;
    z-index: 100;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

#category-filter {
    padding: 5px;
}

#api-table-container {
    max-height: 500px; /* Adjust this value based on your needs */
    overflow-y: auto;
    position: relative;
}

#api-table {
    width: 100%;
    border-collapse: collapse;
}

#api-table th,
#api-table td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
}

#table-head {
    position: -webkit-sticky; /* For Safari */
    position: sticky;
    top: 0;
    background-color: #f1f1f1;
    z-index: 100;
}

کد جاوااسکریپت:

document.addEventListener('DOMContentLoaded', function () {
    const apiUrl = 'https://api.publicapis.org/entries';
    const apiListContainer = document.getElementById('api-list');
    const categoryFilter = document.getElementById('category-filter');
    const tableHead = document.getElementById('table-head');
    const filterButton = document.getElementById('filter-button');
    const refreshButton = document.getElementById('refresh-button');
    const apiTableContainer = document.getElementById('api-table-container');

    let apiData = [];
    let filteredData = [];
    let startIndex = 0;
    const itemsPerPage = 50;

    function fetchData(startIndex, endIndex) {
        return fetch(apiUrl)
            .then(response => response.json())
            .then(data => {
                console.log('API Data:', data);
                apiData = data.entries;
                filteredData = apiData.slice(startIndex, endIndex);
                console.log('Filtered Data:', filteredData);
                return filteredData;
            })
            .catch(error => {
                console.error('Error fetching data:', error);
                return [];
            });
    }

    function displayData(data) {
        console.log('Displaying Data:', data);
        apiListContainer.innerHTML = '';
        data.forEach((api, index) => {
            const row = document.createElement('tr');
            const numberCell = document.createElement('td');
            numberCell.textContent = startIndex + index + 1;
            row.appendChild(numberCell);

            for (const key in api) {
                if (api.hasOwnProperty(key)) {
                    const cell = document.createElement('td');
                    cell.textContent = api[key];
                    row.appendChild(cell);
                }
            }
            apiListContainer.appendChild(row);
        });
    }

    function populateCategories(data) {
        const categories = [
            "Animals", "Anime", "Anti-malware", "Art & Design", "Authentication & Authorization",
            "Blockchain", "Books", "Business", "Calendar", "Cloud storage & File sharing",
            "Continuous Integration", "Cryptocurrency", "Currency Exchange", "Data Validation",
            "Development", "Dictionaries", "Documents & Productivity", "Email", "Entertainment",
            "Environment", "Events", "Finance", "Food & Drink", "Games & Comics", "Geocoding",
            "Government", "Health", "Jobs", "Machine Learning", "*****", "News", "Open Data",
            "Open Source Projects", "Patent", "Personality", "Phone", "Photography", "Programming",
            "Science & Math", "Security", "Shopping", "Social", "Sports & Fitness", "Text Data",
            "Text Analysis", "Tracking", "Transportation", "URL Shorteners", "Vehicle", "Video",
            "Weather"
        ];

        categories.forEach(category => {
            const option = document.createElement('option');
            option.value = category;
            option.textContent = category;
            categoryFilter.appendChild(option);
        });
    }

    function refreshData() {
        fetchData(startIndex, startIndex + itemsPerPage)
            .then(newData => {
                startIndex += itemsPerPage;
                displayData(newData);
                window.scrollTo(0, 55); // Scroll to the top of the page with an offset
            });
    }

    function applyFilter() {
        const selectedCategory = categoryFilter.value;
        filteredData = apiData.filter(api => selectedCategory === 'all' || api.category === selectedCategory);
        startIndex = 0; // Reset startIndex when applying a filter
        displayData(filteredData);
    }

    filterButton.addEventListener('click', applyFilter);
    refreshButton.addEventListener('click', refreshData);

    window.addEventListener('resize', function () {
        displayData(filteredData.slice(startIndex, startIndex + itemsPerPage));
    });

    fetch(apiUrl)
        .then(response => response.json())
        .then(data => {
            console.log('Initial Data:', data.entries);
            if (data.entries.length > 0) {
                const firstEntry = data.entries[0];
                const numberTh = document.createElement('th');
                numberTh.textContent = 'Number';
                tableHead.appendChild(numberTh);

                for (const key in firstEntry) {
                    if (firstEntry.hasOwnProperty(key)) {
                        const th = document.createElement('th');
                        th.textContent = key;
                        tableHead.appendChild(th);
                    }
                }
            }
            fetchData(0, itemsPerPage)
                .then(initialData => {
                    displayData(initialData);
                    populateCategories(data.entries);
                });
        })
        .catch(error => console.error('Error fetching initial data:', error));

    window.addEventListener('scroll', function () {
        const scrollPosition = window.scrollY;
        tableHead.style.position = scrollPosition > 55 ? 'fixed' : 'static';
        tableHead.style.top = '0';
    });
});

</body></html>


ثبت پرسش جدید

به همدیگه کمک کنیم

به fara کمک کنید تا مشکل خودش را حل کند؛ این‌طور می‌توانیم با هم پیشرفت کنیم.

برای ارسال پاسخ لازم است وارد شده یا ثبت‌نام کنید

ورود یا ثبت‌نام