[英]Getting return value from inside [an ajax] function
如何从函数中获取“ 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或回调方法来实现。 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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.