News now ajax

Here's an example of how to use AJAX (Asynchronous JavaScript and XML) to fetch and display the latest news headlines:

HTML

<div id="news-headlines"></div>

JavaScript

// Set the URL for the news API
const url = 'https://newsapi.org/v2/top-headlines?country=us&apiKey=YOUR_API_KEY';

// Function to fetch and display the news headlines
function getNewsHeadlines() {
  // Create an XMLHttpRequest object
  const xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.onload = function() {
    if (xhr.status === 200) {
      const response = JSON.parse(xhr.responseText);
      const newsHeadlines = response.articles;
      const newsHTML = '';
      newsHeadlines.forEach((article) => {
        newsHTML += `
          <h2>${article.title}</h2>
          <p>${article.description}</p>
          <a rel="nofollow" target="_blank" href="${article.url}">Read more</a>
        `;
      });
      document.getElementById('news-headlines').innerHTML = newsHTML;
    }
  };
  xhr.send();
}

// Call the function to fetch and display the news headlines
getNewsHeadlines();

Explanation

  1. We set the URL for the news API, which returns a JSON response containing the latest news headlines.
  2. We create an XMLHttpRequest object and set the URL, method (GET), and asynchronous flag (true) using the open() method.
  3. We set the event listener for the onload event, which is triggered when the request is complete.
  4. In the onload event handler, we parse the JSON response using JSON.parse() and extract the news headlines from the response.
  5. We loop through the news headlines and create an HTML string for each article, including the title, description, and a link to read more.
  6. We set the innerHTML of the #news-headlines div to the HTML string using document.getElementById().

Note