我正在处理大型数据文件时出现时间问题。有时,“getFileData(selectedFile)”之后的语句在下载文件之前执行,并且语句失败。我正在考虑一个“暂停”功能,但必须有更好的东西。javascript http请求滞后
$("#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();
}
你应该将所有依赖于你的VAR文本的回调函数的代码:xmlhttp.onreadystatechange - 你的XMLHTTP请求是非阻塞[这是很好] - 你通过在这里传递true告诉它是异步的:xmlhttp.open(“GET”,url +“?q =”+ fileName +“.txt”,true); – 2014-10-10 23:52:30
XMLHttpRequest()本质上是异步的。您应该考虑使用回调模式(如pep的回答+1所示)或使用promise。 – JME 2014-10-10 23:59:52