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

FreeCodeCamp Wiki项目JS问题:原生JS获取用户输入调用Wiki API

Fixing User Input for Wiki API Calls in FreeCodeCamp's Wiki App

Hey there! I totally get where you’re coming from—having manual API calls work but not user input is such a frustrating roadblock. Let’s walk through how to get this sorted with plain vanilla JavaScript, step by step.

Step 1: Grab Your DOM Elements First

First, you need to reference the input field and either a search button or the form itself in your JS. This lets you access what the user types. For example:

// Get the input field (replace with your actual ID)
const searchInput = document.getElementById('wiki-search-input');
// Get the search button (or use the form for submit support)
const searchBtn = document.getElementById('search-button');
// Or grab the form to handle enter key submissions
const searchForm = document.getElementById('search-form');

Step 2: Listen for User Interaction

You need to trigger the API call when the user clicks the search button or hits enter. Using the form’s submit event is better because it supports both actions—just don’t forget to stop the form from reloading the page!

// Option 1: Listen for button click
searchBtn.addEventListener('click', handleSearch);

// Option 2: Listen for form submit (recommended for accessibility)
searchForm.addEventListener('submit', (e) => {
  e.preventDefault(); // Critical! Stops the page from reloading
  handleSearch();
});

Step 3: Build the API Call with User Input

Now write the handleSearch function that grabs the user’s input, cleans it up, and builds a valid API URL. The key here is encoding the search term to handle spaces and special characters (like apostrophes or symbols) that would break the URL.

function handleSearch() {
  // Get and trim the input value to remove extra spaces
  const searchTerm = searchInput.value.trim();
  
  // Don't run the call if the input is empty
  if (!searchTerm) {
    alert('Please enter something to search!');
    return;
  }

  // Build the Wiki API URL with encoded search term
  const apiUrl = `https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${encodeURIComponent(searchTerm)}&format=json&origin=*`;

  // Use fetch (modern native JS) to make the AJAX call
  fetch(apiUrl)
    .then(response => {
      if (!response.ok) {
        throw new Error('Whoops, something went wrong with the request!');
      }
      return response.json();
    })
    .then(data => {
      // Pass the results to a function to display them
      displaySearchResults(data.query.search);
    })
    .catch(error => {
      console.error('Error fetching data:', error);
    });
}

Step 4: Display the Results

Finally, write a function to render the search results to the page. Here’s a simple example:

function displaySearchResults(results) {
  const resultsContainer = document.getElementById('results-container');
  // Clear any previous results
  resultsContainer.innerHTML = '';

  results.forEach(result => {
    const resultCard = document.createElement('div');
    resultCard.classList.add('result-card');
    // Link to the full Wikipedia page (encode the title too!)
    const wikiLink = `https://en.wikipedia.org/wiki/${encodeURIComponent(result.title)}`;
    resultCard.innerHTML = `
      <h3><a href="${wikiLink}" target="_blank">${result.title}</a></h3>
      <p>${result.snippet}</p>
    `;
    resultsContainer.appendChild(resultCard);
  });
}

Key Things to Remember

  • encodeURIComponent() is non-negotiable: It converts user input into a URL-safe string—without it, spaces or special characters will make your API call fail.
  • Prevent form default behavior: If you use a form, always call e.preventDefault() to stop the page from reloading before your AJAX call runs.
  • Handle empty input: Don’t waste an API call on an empty search term—add a quick check to alert the user.

If you prefer using XMLHttpRequest instead of fetch, here’s a quick alternative for the AJAX part:

// XMLHttpRequest version of the API call
function handleSearch() {
  const searchTerm = searchInput.value.trim();
  if (!searchTerm) {
    alert('Please enter a search term!');
    return;
  }

  const apiUrl = `https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${encodeURIComponent(searchTerm)}&format=json&origin=*`;
  const xhr = new XMLHttpRequest();

  xhr.open('GET', apiUrl, true);
  xhr.onload = function() {
    if (xhr.status >= 200 && xhr.status < 400) {
      const data = JSON.parse(xhr.responseText);
      displaySearchResults(data.query.search);
    } else {
      console.error('Server returned an error');
    }
  };

  xhr.onerror = function() {
    console.error('Network error occurred');
  };

  xhr.send();
}

Give this a shot—this should connect your user input to the Wiki API call smoothly!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:37:35