如何通过Fetch将Django视图返回的JSON数据传递至JavaScript?
Fetching Django JSON Data with the Fetch API
Great question! Let's get your Django view's JSON response into your JavaScript code smoothly. Here's a step-by-step breakdown:
Step 1: Ensure Your View is Mapped to a URL
First, make sure your view is connected to a URL in your app's urls.py so the frontend can reach it:
# urls.py from django.urls import path from . import views from django.contrib.auth.decorators import login_required # Add the @login_required decorator to your view (critical since it uses request.user) @login_required def get_all_monitors_with_last_data(request): # ... your existing view code urlpatterns = [ # ... other app URLs path('api/monitors/', get_all_monitors_with_last_data, name='fetch_monitors'), ]
Step 2: Write the Fetch API Code in JavaScript
Use the Fetch API to call your Django endpoint, handle authentication, and process the JSON response. Here's a complete, robust example:
// In your JavaScript file (e.g., app.js) async function loadMonitorsData() { try { // Call your Django API endpoint const response = await fetch('/api/monitors/', { method: 'GET', credentials: 'include', // Sends session cookies so Django recognizes the logged-in user headers: { 'Accept': 'application/json', // Tell Django we expect JSON back } }); // Check if the request was successful if (!response.ok) { throw new Error(`Request failed: ${response.status} ${response.statusText}`); } // Parse the JSON response const monitorsData = await response.json(); // Use the data however you need! console.log('Fetched monitor data:', monitorsData); // Example: Render data to the DOM // renderMonitorsToPage(monitorsData); } catch (error) { // Handle errors (network issues, unauthenticated requests, etc.) console.error('Error loading monitor data:', error); alert('Failed to load monitor data. Please try again later.'); } } // Run the function when the page finishes loading document.addEventListener('DOMContentLoaded', loadMonitorsData);
Key Details to Note:
credentials: 'include': This is mandatory for authenticated views. It ensures the browser sends the session cookie with the request, so Django can identifyrequest.userand grant access.- Error Handling: We check for HTTP errors (like 401 Unauthorized or 500 Server Error) and network failures to keep your app resilient.
- CSRF Protection for POST Requests: If you ever switch this view to accept POST requests, add the CSRF token to your Fetch headers:
const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value; const response = await fetch('/api/monitors/', { method: 'POST', credentials: 'include', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': csrfToken }, // Optional: Send data in the request body // body: JSON.stringify({ filter: 'active' }) });
Testing Tip
Before debugging your JavaScript, test the endpoint directly in your browser (while logged in) by visiting /api/monitors/. You should see the raw JSON response—this confirms your Django view is working correctly.
内容的提问来源于stack exchange,提问作者Mauricio Romero
相关产品推荐
相关产品推荐

