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

纯JavaScript读取JSON URL数据并在HTML中展示入门指导请求

How to Fetch JSON Data from a URL and Display It in HTML with Plain JavaScript (Beginner-Friendly Guide)

Hey there! I totally get it—when you're just starting out with JavaScript, figuring out how to pull data from a JSON URL and show it on a page can feel overwhelming. Let's break this down step by step with simple, hands-on examples so you can build this yourself without stress.


Step 1: Set Up Your Basic HTML Structure

First, create an HTML file with a dedicated spot where we'll display our fetched data. We'll use a <div> with an ID so we can easily target it with JavaScript later.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSON Data Display</title>
    <!-- Add some basic styling if you want -->
    <style>
        #data-container {
            margin: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        li {
            margin: 10px 0;
            list-style: none;
            padding: 8px;
            background: #f5f5f5;
            border-radius: 3px;
        }
    </style>
</head>
<body>
    <h1>My JSON Data</h1>
    <!-- This is where our fetched data will live -->
    <div id="data-container"></div>

    <!-- We'll add our JavaScript right here -->
    <script>
        // Our code will go here soon!
    </script>
</body>
</html>

Step 2: Use the fetch() API to Grab JSON Data

The fetch() API is built into modern browsers and is the easiest way for beginners to get data from a URL. Here's how to use it inside the <script> tag:

// Replace this with your JSON file URL (local or remote)
// For testing, create a data.json file in the same folder as your HTML
const jsonUrl = 'data.json';

// Fetch the data from the URL
fetch(jsonUrl)
    .then(response => {
        // First, check if the request worked successfully
        if (!response.ok) {
            throw new Error(`Something went wrong! Status: ${response.status}`);
        }
        // Convert the raw response into JSON format
        return response.json();
    })
    .then(data => {
        // Pass the JSON data to our display function
        displayData(data);
    })
    .catch(error => {
        // Handle errors (like broken links or network issues)
        const container = document.getElementById('data-container');
        container.innerHTML = `<p>Oops! Couldn't load data: ${error.message}</p>`;
    });

Step 3: Create a Function to Display the Data

Now we need a function to take our JSON data and render it into the HTML container. Let's cover two common JSON scenarios: arrays of objects (like a list of users) and single objects.

First, here's an example of what your data.json might look like:

[
    { "name": "Alice", "age": 28, "favoriteHobby": "Painting" },
    { "name": "Bob", "age": 32, "favoriteHobby": "Hiking" }
]

Add this displayData() function right below the fetch code:

function displayData(data) {
    const container = document.getElementById('data-container');

    // If the data is an array (like our example above)
    if (Array.isArray(data)) {
        let html = '<h3>User List</h3><ul>';
        // Loop through each item in the array
        data.forEach(item => {
            html += `
                <li>
                    <strong>Name:</strong> ${item.name}<br>
                    <strong>Age:</strong> ${item.age}<br>
                    <strong>Favorite Hobby:</strong> ${item.favoriteHobby}
                </li>
            `;
        });
        html += '</ul>';
        container.innerHTML = html;
    } else {
        // If the data is a single object (e.g., one user's details)
        let html = '<h3>Single User Details</h3>';
        for (const key in data) {
            html += `<p><strong>${key}:</strong> ${data[key]}</p>`;
        }
        container.innerHTML = html;
    }
}

Key Tips for Beginners

  • Local Testing: Start with a local data.json file in the same folder as your HTML to avoid CORS errors (these happen when you try to fetch data from a different domain without permission).
  • Async/Await Alternative: Once you're comfortable with .then() syntax, you can try async/await which reads more like regular code:
    async function fetchAndDisplay() {
        try {
            const response = await fetch(jsonUrl);
            if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
            const data = await response.json();
            displayData(data);
        } catch (error) {
            const container = document.getElementById('data-container');
            container.innerHTML = `<p>Oops! Couldn't load data: ${error.message}</p>`;
        }
    }
    fetchAndDisplay();
    
  • Loading States: Add a "Loading..." message before fetching data to let users know something's happening:
    // Add this right before the fetch call
    const container = document.getElementById('data-container');
    container.innerHTML = '<p>Loading data...</p>';
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:46:15