提取大型数据文件时,我似乎遇到了时间问题。有时,“ getFileData(selectedFile)”之后的语句在下载文件之前执行,并且该语句失败。我正在考虑“暂停”功能,但必须有更好的选择。

$("#dropDown").change(function (){
  var selectedFile = $("#dropDown").val();
  var text = getFileData(selectedFile);

  var valueLength = text.constructs[0].data_sections[0].values.length;
  var errorLength = text.constructs[0].data_sections[0].errors.length;
   . . . .
   . . . .
   . . . .

});

var getFileData = function(fileName){

   var xmlhttp = new XMLHttpRequest();
   var url = "http://xxx/xxx.php";

xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var response = JSON.parse(xmlhttp.responseText.substr(0,xmlhttp.responseText(indexOf("<")));
        return response;
    }
}
xmlhttp.open("GET", url + "?q=" + fileName + ".txt", true);
xmlhttp.send();


}

最佳答案

没错,有更好的方法:回调函数。如果您不熟悉回调,则下面的代码可能没有任何意义。我尚未对其进行测试,但是它应该可以工作,或者至少可以接近。查阅此内容以获得有关回调http://www.impressivewebs.com/callback-functions-javascript/的参考。

$("#dropDown").change(function (){
  var selectedFile = $("#dropDown").val();
  var text = getFileData(selectedFile, function(response){
    //stuff that should not execute until XMLHttpRequest completes
    var valueLength = response.constructs[0].data_sections[0].values.length;
    var errorLength = response.constructs[0].data_sections[0].errors.length;
     . . . .
     . . . .
     . . . .
  });
});

var getFileData = function(fileName, callback){

   var xmlhttp = new XMLHttpRequest();
   var url = "http://xxx/xxx.php";

   xmlhttp.onreadystatechange=function() {
       if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
           var response = JSON.parse(xmlhttp.responseText.substr(0,xmlhttp.responseText(indexOf("<")));
           callback(response);
       }
   }
   xmlhttp.open("GET", url + "?q=" + fileName + ".txt", true);
   xmlhttp.send();
}


实际上,您拥有的代码将永远无法使用。您的getFileData函数将始终在HTTP请求完成之前,因此在您的return语句被命中之前返回。回调模式对学习非常有用,它实际上使您可以提供在延迟后执行的代码,无论延迟是由于HTTP请求,动画还是由您命名。

10-04 22:48
查看更多