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

基于Django REST Framework的django-filter邮编范围查询技术问询

How to Modify JavaScript URL Request to Fetch Data for a Zip Code Range (29601-29627)

Hey there! Let's work through adjusting your JavaScript request to pull vendor data for the entire zip code range 29601 to 29627 instead of just the single zip 29615. Here are two practical approaches depending on what your backend API supports:

Option 1: Use Range Parameters (Most Efficient, If Backend Allows)

First, check if your /api/vendor_filter/ endpoint accepts range-based zip code parameters (like zipCodeMin and zipCodeMax). This is the best approach since it only needs one request.

Here's how to update your code:

// Format current date to match your original MM/DD/YYYY pattern
const getFormattedCurrentDate = () => {
  const now = new Date();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const year = now.getFullYear();
  return `${month}/${day}/${year}`;
};

// Define your target zip code range
const zipRange = {
  min: '29601',
  max: '29627'
};

// Build query parameters cleanly
const queryParams = new URLSearchParams({
  city: '',
  zipCodeMin: zipRange.min,
  zipCodeMax: zipRange.max,
  dateServing: getFormattedCurrentDate()
});

// Send the request
fetch(`/api/vendor_filter/?${queryParams}`)
  .then(response => {
    if (!response.ok) throw new Error('Request failed to fetch data');
    return response.json();
  })
  .then(vendorData => {
    console.log('Vendors in zip range:', vendorData);
    // Add your logic to process the returned data here
  })
  .catch(err => console.error('Error loading vendor data:', err));

Option 2: Batch Requests for Individual Zips (If Backend Doesn't Support Ranges)

If your API only accepts a single zipCode per request, you'll need to generate all zips in the 29601-29627 range, send multiple requests, then combine the results.

Here's how to implement that:

// Generate an array of all zips in the target range
const generateZipCodeRange = (startZip, endZip) => {
  const zips = [];
  for (let zip = startZip; zip <= endZip; zip++) {
    zips.push(String(zip).padStart(5, '0')); // Ensure consistent 5-digit format
  }
  return zips;
};

// Reusable date formatting function
const getFormattedCurrentDate = () => {
  const now = new Date();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const year = now.getFullYear();
  return `${month}/${day}/${year}`;
};

// Set up core values
const targetZips = generateZipCodeRange(29601, 29627);
const currentDate = getFormattedCurrentDate();

// Create requests for each zip code
const vendorRequests = targetZips.map(zip => {
  const params = new URLSearchParams({
    city: '',
    zipCode: zip,
    dateServing: currentDate
  });
  return fetch(`/api/vendor_filter/?${params}`)
    .then(res => {
      if (!res.ok) throw new Error(`Failed to fetch data for zip ${zip}`);
      return res.json();
    });
});

// Wait for all requests to finish and combine results
Promise.all(vendorRequests)
  .then(allResults => {
    // Flatten results and remove duplicate vendors (using their ID as a unique key)
    const uniqueVendors = [...new Map(allResults.flat().map(vendor => [vendor.id, vendor])).values()];
    console.log('All unique vendors in zip range:', uniqueVendors);
    // Handle your combined dataset here
  })
  .catch(err => console.error('Batch request failed:', err));

Quick Tips:

  • Check Backend Docs First: Always confirm if your API supports range parameters before using the batch method—it avoids extra requests and potential rate-limiting issues.
  • Date Automation: The code above automatically uses the current date (replacing your hardcoded date) while keeping the same format.
  • Duplicate Prevention: In the batch approach, we use a Map to filter out duplicate vendors that might appear in multiple zip code results.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:43:56