function callAPIurl query var responseTexts = documentgetElementByIdchatgpt-response; var xhr = new XMLHttpRequest; xhropenPOST url true; x
The function callAPI does not have a return statement outside of the xhr.onreadystatechange callback function. Therefore, when the function is called, it does not return anything.
Also note that the return true and return false statements inside the xhr.onreadystatechange callback function will not affect the return value of the callAPI function itself.
If you want the callAPI function to return a value based on the success or failure of the AJAX request, you could modify the function to use a callback function that is called when the request is complete. For example:
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);
}
This version of the callAPI function takes a third argument callback, which is a function that will be called with a boolean value indicating whether the request was successful or not. You can use this callback to perform any additional actions based on the result of the AJAX request.
原文地址: https://www.cveoy.top/t/topic/Z8C 著作权归作者所有。请勿转载和采集!