从[ajax]函数中获取返回值

时间:2017-02-23 11:03:15

标签: javascript jquery ajax api

如何获得" 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;
    }
  }
}




1 个答案:

答案 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 
});