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

如何使用AJAX调用Postcodes.io API实现批量邮编查询?

Batch Postcode Lookup with Postcodes.io & AJAX

Got it, let's get your batch postcode lookup sorted out efficiently. You're spot-on about the batch endpoint needing a JSON object with a postcodes array—let's build directly on your existing code to handle 200 postcodes (split into two batches of 100, since that's the API's per-request limit).

Step 1: Split Postcodes into Batches

First, we'll need a simple helper function to split your full list into chunks of 100. This keeps us within the API's constraints:

function chunkArray(arr, chunkSize) {
  const chunks = [];
  for (let i = 0; i < arr.length; i += chunkSize) {
    chunks.push(arr.slice(i, i + chunkSize));
  }
  return chunks;
}

Step 2: Reusable Batch Request Function

Next, let's create a function that handles a single batch of postcodes. This uses the batch endpoint (/postcodes with POST) and matches your existing error-handling logic:

function fetchBatch(postcodes) {
  return new Promise((resolve, reject) => {
    $.ajax({
      type: "POST",
      url: "https://api.postcodes.io/postcodes",
      contentType: "application/json", // Critical: tells the API we're sending JSON
      data: JSON.stringify({ postcodes: postcodes }), // Wrap array in the required object
      success: function(response) {
        // The batch response includes a "result" array with entries for each postcode
        const successfulResults = response.result.filter(item => item.status === 200);
        const failedResults = response.result.filter(item => item.status !== 200);
        
        console.log(`Batch done: ${successfulResults.length} successful, ${failedResults.length} failed`);
        resolve({ successful: successfulResults, failed: failedResults });
      },
      error: function(xhr, ajaxOptions, thrownError) {
        let msg = '';
        if (xhr.status === 0) {
          msg = 'Not connect.\n Verify Network.';
        } else if (xhr.status == 404) {
          msg = 'Requested page not found. [404]';
        } else if (xhr.status == 500) {
          msg = 'Internal Server Error [500].';
        } else if (thrownError === 'parsererror') {
          msg = 'Requested JSON parse failed.';
        } else if (thrownError === 'timeout') {
          msg = 'Time out error.';
        } else if (thrownError === 'abort') {
          msg = 'Ajax request aborted.';
        } else {
          msg = 'Uncaught Error.\n' + xhr.responseText;
        }
        console.error('Batch request failed:', msg);
        reject(new Error(msg));
      }
    });
  });
}

Step 3: Run the Full Batch Process

Finally, put it all together to process your 200 postcodes. We'll use Promise.all to run batches in parallel for speed:

// Your full list of 200 postcodes
const allPostcodes = ["BS16AA", "SW1A1AA", "...", /* add all your postcodes here */];

// Split into two batches of 100
const postcodeBatches = chunkArray(allPostcodes, 100);

// Process all batches
Promise.all(postcodeBatches.map(batch => fetchBatch(batch)))
  .then(allResults => {
    // Combine results from both batches
    const allSuccessful = allResults.flatMap(res => res.successful);
    const allFailed = allResults.flatMap(res => res.failed);
    
    console.log(`All batches complete: ${allSuccessful.length} total successful lookups`);
    console.log('Failed lookups (invalid/missing postcodes):', allFailed);
    
    // Add your logic here to use the results (e.g., display on page, save to database)
  })
  .catch(globalError => {
    console.error('One or more batches failed:', globalError.message);
  });

Quick Tips:

  • Content-Type Header: Don't skip contentType: "application/json"—the API won't parse your request correctly without it.
  • Response Structure: For successful entries, access the postcode data via item.result (e.g., item.result.latitude).
  • Rate Limits: Postcodes.io doesn't enforce strict public rate limits, but if you ever run into issues, you can add a small delay between batches using setTimeout.

内容的提问来源于stack exchange,提问作者Mr Dansk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:22:41