如何通过AJAX调用本地JSON文件,用JS生成Bootstrap 4卡片?
Alright, let's put together that local Bootstrap 4 blog list page you're wanting—no server required, just plain files you can open right on your computer. Here's a step-by-step breakdown to make it work:
1. First, Set Up Your Folder Structure
Organize your files like this to keep paths consistent:
your-blog-folder/ ├── index.html # Main blog list page ├── JSON/ │ └── bloglist.json # Stores all your blog post data ├── images/ │ └── blog/ │ ├── blog-article-1.png │ └── ... (other blog post images) └── blog/ ├── blog-article-1.html └── ... (individual blog post pages)
2. Create the Blog Data JSON File
Make sure your JSON/bloglist.json uses valid JSON syntax (double quotes for keys/values, no trailing commas). Here's an example:
{ "articles": [ { "title": "5 Tips for Better Local Web Development", "url": "/blog/blog-article-1.html", "image": "/images/blog/blog-article-1.png", "excerpt": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." }, { "title": "Getting Started with Bootstrap 4 Cards", "url": "/blog/blog-article-2.html", "image": "/images/blog/blog-article-2.png", "excerpt": "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." } ] }
3. Build the Main HTML Page (index.html)
We'll use Bootstrap 4's CDN for styling (no need to download local files) and add a container where our blog cards will be injected:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My Personal Blog</title> <!-- Bootstrap 4 CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"> </head> <body> <div class="container mt-5"> <h1 class="mb-4">Latest Blog Posts</h1> <!-- Blog cards will load here --> <div id="blog-container" class="row"></div> </div> <!-- jQuery (required for Bootstrap 4 JS and easy AJAX) --> <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script> <!-- Bootstrap 4 JS --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script> <!-- Custom script to load blog posts --> <script> $(document).ready(function() { // Fetch blog data from JSON file $.ajax({ url: 'JSON/bloglist.json', dataType: 'json', success: function(data) { const blogContainer = $('#blog-container'); // Loop through each article and build a card data.articles.forEach(article => { const card = ` <div class="col-md-4 mb-4"> <div class="card h-100"> <img src="${article.image}" class="card-img-top" alt="${article.title}"> <div class="card-body"> <h5 class="card-title">${article.title}</h5> <p class="card-text">${article.excerpt}</p> <a href="${article.url}" class="btn btn-primary">Read More</a> </div> </div> </div> `; blogContainer.append(card); }); }, error: function(xhr, status, error) { blogContainer.html('<p class="text-danger">Oops, failed to load posts. Check your JSON file and paths!</p>'); console.error('Load error:', error); } }); }); </script> </body> </html>
Alternative: No jQuery? Use Vanilla JS
If you prefer to skip jQuery, replace the custom script with this vanilla JavaScript version:
document.addEventListener('DOMContentLoaded', function() { const blogContainer = document.getElementById('blog-container'); fetch('JSON/bloglist.json') .then(response => { if (!response.ok) throw new Error('Failed to fetch data'); return response.json(); }) .then(data => { data.articles.forEach(article => { // Build card elements programmatically const col = document.createElement('div'); col.className = 'col-md-4 mb-4'; const card = document.createElement('div'); card.className = 'card h-100'; const img = document.createElement('img'); img.src = article.image; img.className = 'card-img-top'; img.alt = article.title; const body = document.createElement('div'); body.className = 'card-body'; const title = document.createElement('h5'); title.className = 'card-title'; title.textContent = article.title; const excerpt = document.createElement('p'); excerpt.className = 'card-text'; excerpt.textContent = article.excerpt; const btn = document.createElement('a'); btn.href = article.url; btn.className = 'btn btn-primary'; btn.textContent = 'Read More'; // Assemble the card body.append(title, excerpt, btn); card.append(img, body); col.appendChild(card); blogContainer.appendChild(col); }); }) .catch(error => { blogContainer.innerHTML = '<p class="text-danger">Oops, failed to load posts. Check your JSON file and paths!</p>'; console.error('Load error:', error); }); });
4. Critical Notes for Local Running
- Browser Security Restrictions: Most browsers (like Chrome) block local file AJAX requests by default. To fix this:
- Use Firefox: It allows local file requests out of the box.
- Or start a tiny local server:
- With Python: Open your project folder in terminal and run
python -m http.server(Python 3) orpython -m SimpleHTTPServer(Python 2), then visithttp://localhost:8000. - With Node.js: Run
npx http-serverand visithttp://localhost:8080.
- With Python: Open your project folder in terminal and run
- Validate Your JSON: A single syntax error (like missing quotes or a trailing comma) will break the whole load. Use a free online JSON validator to check your file if things aren't working.
- Double-Check Paths: Make sure all image, blog post, and JSON file paths are relative to
index.html(e.g.,/JSON/bloglist.jsonis correct ifindex.htmlis in the root folder).
内容的提问来源于stack exchange,提问作者Alexis Drakopoulos
相关产品推荐
相关产品推荐

