2015-07-12 77 views
0

我试图运行这个,但它不起作用。 它旨在返回一个在函数内部分配的变量,该变量作为回调函数传递给sendRequest(),该函数通过异步方式通过XMLHttpRequest从Internet检索数据。JavaScript变量不能用XMLHttpRequest更改

谁能告诉我为什么这不起作用,总是返回“”?

function sendRequest(requestCode, args, callback){ 
 
\t var req = requestEngineUrl + "?req=" + requestCode + ";" + args; 
 
\t var xmlHttp = new XMLHttpRequest(); 
 
\t xmlHttp.onreadystatechange = function(){ 
 
\t \t if(xmlHttp.readyState == 4) 
 
\t \t { \t 
 
\t \t \t if(callback != null){ 
 
\t \t \t \t callback(xmlHttp.responseText); 
 
\t \t \t } 
 
\t \t } 
 
\t }; 
 
\t xmlHttp.open("GET", req, true); 
 
\t xmlHttp.send(null); 
 
}

this.assembleProcess = function(){ 
 
\t \t if(!isNull(this.id) && !isNull(this.titles)){ 
 
\t \t \t var titles = this.titles; 
 
\t \t \t var id = this.id; 
 
\t \t \t c = ""; 
 
\t \t \t sendRequest('304', id, 
 
\t \t \t \t function(result){ 
 
\t \t \t \t \t var res = result.split("/"); 
 
\t \t \t \t \t var title = res[0]; 
 
\t \t \t \t \t var possibilities = res[1]; 
 
\t \t \t \t \t var fcontent = title + '<br><div>'; 
 
\t \t \t \t \t \t if(titles.length != possibilities){ 
 
\t \t \t \t \t \t \t console.log("WARNING: [SURVEYCARD].titles has not the same length as possibilities"); 
 
\t \t \t \t \t \t } 
 
\t \t \t \t \t 
 
\t \t \t \t \t \t for(i = 0; i < possibilities; i++){ 
 
\t \t \t \t \t \t \t fcontent += '<div><a onclick="sendRequest("301",' + id + ',' + i + ',null)">' + titles[i] + '</a></div>'; 
 
\t \t \t \t \t \t } 
 
\t \t \t \t \t 
 
\t \t \t \t \t fcontent += '</div>'; 
 
\t \t \t \t \t c = fcontent; 
 
\t \t \t \t }); 
 
\t \t \t return c; 
 
\t \t }

+2

过程是** **同步。发送给'sendRequest()'函数的回调函数将在HTTP请求完成时被调用。 'alert(c)'语句在那段时间之前已经达到* long *。 – Pointy

+0

有没有办法做到这一点? – aprofomo

+0

是的 - 你已经传递了一个回调函数。当回调运行时,内容将可用,并且您可以执行您需要的任何工作。这就是在异步环境中使用回调进行编程的本质。 – Pointy

回答

1

作为一个XMLHttpRequest是异步,你应该写一个异步功能,对于这个问题,像这样的

this.assembleProcess = function(callback){ 
     if(!isNull(this.id) && !isNull(this.titles)){ 
      var titles = this.titles; 
      var id = this.id; 
      c = ""; 
      sendRequest('304', id, 
       function(result){ 
        var res = result.split("/"); 
        var title = res[0]; 
        var possibilities = res[1]; 
        var fcontent = title + '<br><div>'; 
         if(titles.length != possibilities){ 
          console.log("WARNING: [SURVEYCARD].titles has not the same length as possibilities"); 
         } 

         for(i = 0; i < possibilities; i++){ 
          fcontent += '<div><a onclick="sendRequest("301",' + id + ',' + i + ',null)">' + titles[i] + '</a></div>'; 
         } 

        fcontent += '</div>'; 
        c = fcontent; 
        callback(c) 
       }); 
     } 

,然后,而不是使用this.assembleProcess与结果的功能,你应该通过一个函数作为参数:

代替

console.log(this.assembleProcess); 

做到这一点

this.assembleProcess(function(c){console.log(c)});