function getName(user_id) {
// data
var data = {}
data.user_id = user_id
data = JSON.stringify(data)
// send
const request = new XMLHttpRequest();
request.open("POST", "/test-ajax/");
request.send(data);
// get
request.onload = function() {
var name = JSON.parse(this.response)
console.log(name) // <<< тут данные есть
return name
}
}
var user_name = getName(user_id)
console.log(user_name) // <<< undefined
function getName(user_id) {
return new Promise(function(resolve) {
// data
var data = {}
data.user_id = user_id
data = JSON.stringify(data)
// send
const request = new XMLHttpRequest();
request.open("POST", "/test-ajax/");
request.send(data);
request.onload = function() {
var name = JSON.parse(this.response)
resolve(name);
}
});
}
// Дальше работаем через then
getName(user_id).then(data=>console.log(data));
// Или async/await
const name = await getName(user_id);
function getName(user_id, callback) {
// data
var data = {}
data.user_id = user_id
data = JSON.stringify(data)
// send
const request = new XMLHttpRequest();
request.open("POST", "/test-ajax/");
request.send(data);
// get
request.onload = function() {
var name = JSON.parse(this.response)
callback(name)
}
}
var onNameLoaded = function(name) {
console.log(name)
};
getName(user_id, onNameLoaded);
async function getName(userId) {
const response = await fetch("/test-ajax/", {
method: "POST",
body: JSON.stringify({"user_id": userId})
})
return await response.json();
}
const name = await getName(userId);