Technology Encyclopedia Home >How to make AJAX request using JavaScript?

How to make AJAX request using JavaScript?

To make an AJAX (Asynchronous JavaScript and XML) request using JavaScript, you can utilize the XMLHttpRequest object or the more modern fetch API. AJAX allows you to send and receive data from a server without having to reload the entire page.

Using XMLHttpRequest

Here's a basic example of how to make an AJAX request using XMLHttpRequest:

// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Configure it: GET-request for the URL /data.json
xhr.open('GET', '/data.json', true);

// Set up the callback function to handle the response
xhr.onload = function() {
  if (xhr.status === 200) {
    // Parse the JSON response
    var data = JSON.parse(xhr.responseText);
    console.log(data);
  } else {
    console.error('Error fetching data');
  }
};

// Send the request
xhr.send();

Using Fetch API

The fetch API provides a more modern and promise-based approach to making AJAX requests:

// Make a GET request using fetch
fetch('/data.json')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });

Example with Tencent Cloud

If you're working with cloud services, for example, using Tencent Cloud's Object Storage (COS), you might make an AJAX request to fetch data from a bucket:

fetch('https://example-1250000000.cos.ap-guangzhou.myqcloud.com/test.txt')
  .then(response => response.text())
  .then(data => {
    console.log('File content:', data);
  })
  .catch(error => {
    console.error('Error fetching file:', error);
  });

In this example, example-1250000000.cos.ap-guangzhou.myqcloud.com is the COS bucket endpoint, and test.txt is the file you want to fetch.

Using these methods, you can efficiently make asynchronous requests to servers and handle responses without reloading the page, enhancing the user experience of your web applications.