我正在尝试构建一个函数,该函数将POST请求发送到服务器并从服务器返回响应。我正在使用XMLHttpRequest,并且已成功将请求发送到服务器,并获得了响应。我的问题是我可以在控制台中打印响应,但无法返回它。这是我的代码:
function submitUserInputs(form, url) {
let data = serializeArray(form);
let requestBody = {};
data.forEach((value) => {
if (value.name !== "csrfmiddlewaretoken") {
requestBody[value.name] = value.value
}
});
//send request
let request = new XMLHttpRequest();
request.open("POST", url, "true");
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.setRequestHeader('X-CSRFToken', csrfcookie());
request.send(JSON.stringify(requestBody));
request.onreadystatechange = function () {
if (request.readyState === XMLHttpRequest.DONE) {
return request.responseText;
}
};
}
当我调用此函数时,我总是得到undefined
。知道如何解决这个问题吗?