This function provides a structured way to make an API call using XMLHttpRequest in JavaScript.

function callAPI(url, query, callback) {
    var responseTexts = document.getElementById('chatgpt-response');
    var xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);
    xhr.setRequestHeader(
        'Content-Type',
        'application/json;charset=UTF-8'
    );
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var json = JSON.parse(xhr.responseText);
            var response = json.data.answer;
            responseTexts.innerHTML = '';
            printMessage(response);
            callback(true);
        } else if (xhr.readyState === 4) {
            callback(false);
        }
    };

    var data = JSON.stringify({
        query: query,
    });
    xhr.send(data);
}

Function Arguments:

  • url: The URL of the API endpoint to be called.
  • query: An object containing the query parameters to be passed in the request body.
  • callback: A function that will be executed upon completion of the request, accepting a boolean value indicating success or failure.

Key Function Logic:

  1. Request Initialization: A new XMLHttpRequest object is created and configured with the API URL, 'POST' method, and asynchronous execution.
  2. Header Setting: The 'Content-Type' header is set to 'application/json;charset=UTF-8' to specify the request body's format.
  3. Response Handling: The onreadystatechange event handler captures the server's response. It checks for a successful response (readyState 4 and status code 200) and extracts the 'answer' field from the JSON response.
  4. Output and Callback: The extracted response is displayed, and the callback function is invoked with true for success. If the request fails (readyState 4 and non-200 status code), the callback is invoked with false.

How to Use the Function:

// Example API endpoint URL
var apiUrl = 'https://api.example.com/data';

// Query parameters for the API request
var queryParams = { searchTerm: 'example' };

// Function to handle the response
function handleResponse(success) {
    if (success) {
        console.log('API call successful!');
    } else {
        console.error('API call failed!');
    }
}

// Make the API call
callAPI(apiUrl, queryParams, handleResponse);

This function effectively encapsulates API call logic, ensuring proper request formatting, response parsing, and clear error handling for a streamlined development experience.

JavaScript API Call with XMLHttpRequest: Function Breakdown and Usage

原文地址: https://www.cveoy.top/t/topic/mkDe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录