2017-04-25 63 views
-1

我知道,由于异步XMLHTTPRequest的本质,它不可能在JavaScript中返回responseText值。我已经设法通过调用将reponseText粘贴到提供该函数的任何ID的解决方法函数来找到解决该问题的方法。但是现在我又一次遇到了这个问题,因为我需要检索一个JSON文件并返回它的值。我已经尝试将responseText注入到提供的变量中,但它没有工作,我也尝试添加一个“接口类”文件,这将为我做到这一点,但以上都没有工作。有没有知道解决方法的问题?native javascript return http.responseText

function httpGetJson(file, type) { 
     self.httpState(true); 
     try{ 
      var type = type || true; 
      var http = self.http(); 
      http.onreadystatechange = function() { 
       if (this.readyState == 4 && this.status == 200){ 
        returnJson(this.responseText); 
       } 
      } 
      http.open("GET", "json/" + file, type); 
      http.send(); 
     }catch (err){ 
      return log.error("http.httpGetJson", err.message); 
     } 
     self.httpState(false); 
    } 

看到codepen http://codepen.io/mecostav/pen/JNdovR

回答

0

您应该添加一个回调,或承诺所有。例如,你的函数接收功能

function httpGetJson(file, type, cb) { 
    self.httpState(true); 
    try{ 
     var type = type || true; 
     var http = self.http(); 
     http.onreadystatechange = function() { 
      if (this.readyState == 4 && this.status == 200){ 
       cb(this.responseText); 
      } 
     } 
     http.open("GET", "json/" + file, type); 
     http.send(); 
    }catch (err){ 
     return log.error("http.httpGetJson", err.message); 
    } 
    self.httpState(false); 
} 

然后你就可以把它叫做:

httpGetJson('foo', 'bar', function (result) { 
    // do something with result 
}); 

相反的:

var result = httpGetJson('foo', 'bar'); 
// do something with result 

后者将根本无法与JS,不要上班”试着去“克服”那个。 如果你真的想要它,有一个不推荐的方法来执行同步http请求,你可以谷歌(但请,不要)。

+0

我知道同步请求,并试图避免这些不惜一切代价,因为UX将会急剧恶化。 –