如何获得" res"的返回值?从功能。当我尝试访问它时,它显示未定义。
function solution() {
var url = "https://translate.yandex.net/api/v1.5/tr.json/translate",
keyAPI = "abcdefgh"
var xhr = new XMLHttpRequest(),
textAPI = "some text",
langAPI = "fr"
data = "key=" + keyAPI + "&text=" + textAPI + "&lang=" + langAPI;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var res = this.responseText;
return res;
}
}
}

答案 0 :(得分:0)
您可以尝试这种方式。希望它的作品 -
所以你的XHR
函数有一个回调函数来获取返回值,
function solution(callback) {
var url = "https://translate.yandex.net/api/v1.5/tr.json/translate",
keyAPI = "abcdefgh";
var xhr = new XMLHttpRequest(),
textAPI = "some text",
langAPI = "fr";
data = "key=" + keyAPI + "&text=" + textAPI + "&lang=" + langAPI;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var res = this.responseText;
callback(res);
}
}
}
当您调用XHR
函数时:
solution(function(response){
// you will get the response over here
});