为什么当async标志设置为false时,xmlhttprequest中的代码可以工作,而当它设置为true时却不能工作

Why does the code inside xmlhttprequest work when async flag is set to false but not when it is set to true

本文关键字:设置 工作 true 不能 标志 async false xmlhttprequest 为什么 代码      更新时间:2023-09-26

我对javascript的使用相当陌生,如果有任何帮助,我将不胜感激。我有一个应用程序,浏览器必须使用xmlhttprequest从服务器接收响应(出于测试目的为true/false),根据响应,客户端将打开一个文件选择对话框,供用户选择本地文件进行上传。

当我创建异步标志设置为FALSE的XMLHttpRequest时,当客户端从服务器接收到"true"响应时,会打开一个文件选择对话框(适用于Chrome和IE)。

当我创建异步标志设置为TRUE(推荐)的XMLHttpRequest时,当客户端从服务器接收到"TRUE"响应时,会遵循相同的代码路径,但文件选择对话框永远不会打开,Chrome的调试器中也不会显示错误,但它在IE中仍然有效。

这是代码:

... 
// user has clicked button to upload a file
$scope.uploadFile = function () { 
   request = new XMLHttpRequest();
   request.open("GET", "some-url", true);// false
   request.onreadystatechange = $scope.checkUploadPermissions;
   request.send();    
}
// the callback
// If the user has permission (based on various factors not shown here)
//   we open the dialog
// Otherwise we inform them that they are not allowed
$scope.checkUploadPermissions = function () {
  // simplified for brevity
  if (request.readyState == 4 && request.status == 200) {
    // for this sample, we are only checking if the server returned true/false
    var hasPerms = request.responseText;
    if (hasPerms === "true") {
       $scope.openFileSelector();
    }
    else {
       alert("You do not have permission to upload a file.");
    }
  }
}
// if the user has permission to proceed, we trigger a click on a hidden element
$scope.openFileSelector = function () {       
   angular.element("#presentUpload").trigger("click");
}
...

我想重申的是,当异步标志设置为FALSE时,这段代码非常有效,但当它设置为TRUE时就不行了。

当将标志设置为TRUE时,我如何才能正常工作。

提前谢谢。

文件上传是浏览器中的一项功能,只能作为用户操作的直接结果启动(通常是在JS代码处理鼠标点击或键盘事件时)。它不能由计时器或某些异步回调异步启动。

因此,当您将第一个Ajax调用设置为同步时,JS对隐藏元素的点击会显示在浏览器中,因为它仍在隐藏元素点击事件中,因此允许上传。当您的第一个Ajax调用设置为async时,当您尝试单击隐藏元素时,用户单击事件已经结束,浏览器将不会显示上载对话框。

有关详细信息,请参阅异步ajax done上的触发器点击input=file()。