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
- We set the URL for the news API, which returns a JSON response containing the latest news headlines.
- We create an XMLHttpRequest object and set the URL, method (GET), and asynchronous flag (true) using the
open()
method. - We set the event listener for the
onload
event, which is triggered when the request is complete. - In the
onload
event handler, we parse the JSON response usingJSON.parse()
and extract the news headlines from the response. - We loop through the news headlines and create an HTML string for each article, including the title, description, and a link to read more.
- We set the innerHTML of the
#news-headlines
div to the HTML string usingdocument.getElementById()
.
Note
- Replace
YOUR_API_KEY
with your actual API key from the news API provider. - This example uses the News API (https://newsapi.org/) as the news source. You can use other APIs or services that provide news headlines.
- This is a basic example and you may want to add error handling, caching, and other features depending on your requirements.