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

如何在JavaScript AJAX代码中显示选定国家的城市名称与人口数据

Fix: Display Top 10 Cities with Population in a Table

I see exactly what's going on here — right now you're just dumping raw JSON text into the table element instead of parsing it and building structured table rows with city names and populations. Let's fix this step by step, and also clean up redundant code along the way.

Step 1: Fix the JSON Parsing & Table Generation Logic

Your commented-out table code was heading in the right direction, but had a few bugs (like referencing obj instead of your parsed array, and a typo docoument). Here's the corrected, working version for a single country, then we'll make it reusable:

"use strict;"
function displayUSAInfo() {
  document.getElementById("country_name").innerHTML = "USA";
  const xhttp = new XMLHttpRequest();
  xhttp.onload = function() {
    if (this.readyState === 4 && this.status === 200) {
      try {
        // Parse the JSON response into an array of city objects
        const cities = JSON.parse(this.responseText);
        // Build the table header and rows
        let table = "<tr><th>City</th><th>Population</th></tr>";
        // Loop through each city to add rows
        for (let i = 0; i < cities.length; i++) {
          table += `<tr><td>${cities[i].City}</td><td>${cities[i].Population}</td></tr>`;
        }
        // Insert the completed table into the DOM
        document.getElementById("country_data").innerHTML = table;
      } catch (error) {
        // Handle invalid JSON errors
        document.getElementById("country_data").innerHTML = "<tr><td colspan='2'>Error loading city data. Check your JSON file.</td></tr>";
        console.error("JSON parsing issue:", error);
      }
    }
  }
  xhttp.open("GET", "usa.txt", true);
  xhttp.send();
}

Step 2: Eliminate Redundant Code

You have four nearly identical functions — let's refactor them into one reusable function to make your code cleaner and easier to maintain:

"use strict;"
// Reusable function to load and display any country's city data
function displayCountryInfo(countryName, dataFile) {
  document.getElementById("country_name").innerHTML = countryName;
  const xhttp = new XMLHttpRequest();
  
  xhttp.onload = function() {
    if (this.readyState === 4 && this.status === 200) {
      try {
        const cities = JSON.parse(this.responseText);
        let table = "<tr><th>City</th><th>Population</th></tr>";
        // Use forEach for cleaner iteration
        cities.forEach(city => {
          table += `<tr><td>${city.City}</td><td>${city.Population}</td></tr>`;
        });
        document.getElementById("country_data").innerHTML = table;
      } catch (error) {
        document.getElementById("country_data").innerHTML = "<tr><td colspan='2'>Failed to parse city data.</td></tr>";
        console.error(error);
      }
    } else {
      document.getElementById("country_data").innerHTML = "<tr><td colspan='2'>Error fetching data. Please try again.</td></tr>";
    }
  };

  // Handle network errors
  xhttp.onerror = function() {
    document.getElementById("country_data").innerHTML = "<tr><td colspan='2'>Network error occurred.</td></tr>";
  };

  xhttp.open("GET", dataFile, true);
  xhttp.send();
}

Then update your HTML radio buttons to use this single function:

<div id="content">
  <header>
    <h1><strong>Using AJAX</strong></h1>
  </header>
  <br>
  <main>
    <div class="country_selection">
      <h3>Select a country to get data on their populous cities: </h3>
      <form>
        <input type="radio" name="country" value="usa" onclick="displayCountryInfo('USA', 'usa.txt')"> USA
        <input type="radio" name="country" value="canada" onclick="displayCountryInfo('Canada', 'canada.txt')"> Canada
        <input type="radio" name="country" value="russia" onclick="displayCountryInfo('Russia', 'russia.txt')"> Russia
        <input type="radio" name="country" value="mexico" onclick="displayCountryInfo('Mexico', 'mexico.txt')"> Mexico
      </form>
      <div id="country_name"></div>
      <table id="country_data"></table>
    </div>
  </main>
</div>

Step 3: Validate Your JSON Files

Make sure each *.txt file contains a valid JSON array of city objects, like this example for usa.txt:

[
  {"City": "New York", "Population": 8336817},
  {"City": "Los Angeles", "Population": 3971883},
  {"City": "Chicago", "Population": 2693976},
  {"City": "Houston", "Population": 2320268},
  {"City": "Phoenix", "Population": 1680992},
  {"City": "Philadelphia", "Population": 1584138},
  {"City": "San Antonio", "Population": 1434625},
  {"City": "San Diego", "Population": 1423851},
  {"City": "Dallas", "Population": 1343573},
  {"City": "San Jose", "Population": 1021795}
]

Key Fixes & Improvements

  • Removed redundant code with a single reusable function
  • Properly parsed JSON responses and built table rows dynamically
  • Added error handling for network issues, invalid JSON, and HTTP errors
  • Used template literals (${}) for cleaner, more readable HTML string construction
  • Fixed the typo docoument → document

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 20:07:33