如何从函数中获取" 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;
}
}
}
您可以使用承诺或回调方法来实现这一目标。Promise
相对较新,并且在所有浏览器中不支持。
承诺方法
function solution() {
return new Promise(function(resolve, reject) {
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) {
var res = this.responseText;
this.status == 200 ? resolve(res) : reject('error');
}
}
});
}
如何获得响应
solution().then(function(res) {
console.log(res);
}, function(err) {
console.log(err);
});
回调方法
function solution(success, failure) {
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) {
var res = this.responseText;
this.status == 200 ? success(res) : error('error');
}
}
}
如何获得响应
solution(function(res) {
console.log(res);
}, function(err) {
console.log(err);
});
您可以这样尝试。希望它的工作 -
因此,您的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
});