Answer the question
In order to leave comments, you need to log in
How to return ajax request response to a variable?
Good afternoon!
I implement the method, it takes the path in the directory, makes a request to the server, passing the path, the server returns the id.
The received response is in a different scope and I cannot put it in a variable that is waiting for a response from a function call.
After all, at the time of assigning the value to the variable, the answer has not yet arrived.
Can you tell me how to deal with such a situation?
var id = getId(relativePath);
function getId(relativePath) {
var jqxhr = $.get("http://192.168.1.1:8080/ContentFileId", {
"relativePath": relativePath
}, null, "text");
return jqxhr.always(function(response) {
if (typeof response == 'string') {
return response;
} else {
console.log(response.responseText);
}
})
}
Answer the question
In order to leave comments, you need to log in
getId(relativePath); - that's not possible. Ajax request is not synchronous, to get its result you have to do like this:
// вместо
console.log(response.responseText);
// присвоить значение
id = response.responseText;
// продолжить выполнение своего кода.
function step1 () {
// some code
$.ajax({
// параметры запроса
success: function (data) {
step2(data);
}
});
}
function step2 (data) {
// some other code
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question