JavaScript API Call with XMLHttpRequest: Function Breakdown and Usage
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:
- Request Initialization: A new
XMLHttpRequestobject is created and configured with the API URL, 'POST' method, and asynchronous execution. - Header Setting: The 'Content-Type' header is set to 'application/json;charset=UTF-8' to specify the request body's format.
- Response Handling: The
onreadystatechangeevent 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. - Output and Callback: The extracted response is displayed, and the callback function is invoked with
truefor success. If the request fails (readyState 4 and non-200 status code), the callback is invoked withfalse.
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.
原文地址: https://www.cveoy.top/t/topic/mkDe 著作权归作者所有。请勿转载和采集!