2017-04-25 23 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將會急劇惡化。 –