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

Chrome控制台可获取员工接口数据,前端仅显首个结果的修复求助

Fix: Display All Matching Employees in index.html

Got it, let's sort out this issue where only the first employee shows up even though your API is sending back all matching data. Since you confirmed the Chrome DevTools Console shows the full list, the problem is definitely in how your main.js is rendering those results. Here's how to fix it step by step:

1. Update the Frontend Rendering Logic in main.js

Chances are your current code is only grabbing the first element from the API response array (like data[0]) instead of looping through all entries. Let's adjust that to render every matching employee:

Example Modified Code

// First, wrap your fetch logic in a function triggered by the submit button
function fetchMatchingEmployees() {
  // Get your form data (adjust this based on your actual form fields)
  const searchQuery = document.getElementById('search-input').value;
  
  fetch('/api/employees', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ query: searchQuery }) // Match your backend's expected payload
  })
  .then(response => {
    if (!response.ok) throw new Error('Failed to fetch employees');
    return response.json();
  })
  .then(employees => {
    const resultContainer = document.getElementById('employee-results');
    
    // Clear previous results first so you don't stack entries on repeated clicks
    resultContainer.innerHTML = '';
    
    // Handle empty results case
    if (employees.length === 0) {
      resultContainer.innerHTML = '<p>No matching employees found.</p>';
      return;
    }
    
    // Loop through ALL employees and render each one
    employees.forEach(employee => {
      const employeeElement = document.createElement('div');
      // Add a class for styling (optional but recommended)
      employeeElement.classList.add('employee-item');
      employeeElement.innerHTML = `
        <h4>${employee.name}</h4>
        <p>Extension: ${employee.extension}</p>
      `;
      resultContainer.appendChild(employeeElement);
    });
    
    // Alternative: Use map() to generate HTML string (more concise)
    // const employeeHtml = employees.map(emp => `
    //   <div class="employee-item">
    //     <h4>${emp.name}</h4>
    //     <p>Extension: ${emp.extension}</p>
    //   </div>
    // `).join('');
    // resultContainer.innerHTML = employeeHtml;
  })
  .catch(error => {
    console.error('Error:', error);
    document.getElementById('employee-results').innerHTML = '<p>Oops, something went wrong fetching data.</p>';
  });
}

// Bind the function to your submit button click
document.getElementById('submit-btn').addEventListener('click', fetchMatchingEmployees);

Key Fixes Here:

  • Removed direct access to employees[0] and replaced it with a loop (forEach or map) to process every entry
  • Added logic to clear previous results before rendering new ones
  • Included handling for empty result sets (so users know when no matches exist)
  • Added error handling to catch network issues or API errors

2. Ensure Your index.html Has a Results Container

Make sure your HTML has a dedicated element to hold the employee list. Add this somewhere on your page:

<!-- Add this to index.html where you want results to appear -->
<div id="employee-results"></div>

<!-- And your submit button should have an ID to bind the click event -->
<button id="submit-btn">Search Employees</button>

3. Double-Check Backend Response Structure (Just to Be Safe)

Since you confirmed the Console shows all data, this is probably fine, but quick sanity check:

  • Ensure your employeeDAO.java returns a list/collection of employees, not a single employee object. For example:
    // Example backend method (adjust to match your actual code)
    public List<Employee> findMatchingEmployees(String query) {
        // Your database query logic here that returns all matches
        return employeeRepository.findByNameContaining(query);
    }
    
  • If your API wraps the array in an object (like {"data": [...], "count": 2}), adjust the frontend to access the array correctly:
    .then(response => response.json())
    .then(apiResponse => {
      const employees = apiResponse.data; // Grab the array from the wrapper object
      // Then proceed with looping as before
    })
    

That's it! After making these changes, clicking the submit button should render every matching employee from your API response.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:57:24