为什么 xmlhttprequest 中的代码在异步标志设置为 false 时有效,但在设置为 true 时无效

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

我对 javascript 的使用还很陌生,希望得到任何帮助。 我有一个应用程序,其中浏览器必须使用 xmlhttprequest 来接收来自服务器的响应(true/false 用于测试目的)并且基于响应,客户端将打开一个文件 selection 对话框供用户使用select 上传本地文件。

当我创建异步标志设置为 FALSE 的 XMLHttpRequest 时,当客户端收到来自服务器的 "true" 响应时,文件 selection 对话框打开(对于 Chrome, IE).

当我创建异步标志设置为 TRUE 的 XMLHttpRequest(如推荐的那样)时,当客户端收到来自服务器的 "true" 响应时,遵循相同的代码路径,但是文件 selection 对话框永远不会打开,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 调用设置为异步时,当您尝试单击隐藏元素时用户单击事件已结束,浏览器将不会弹出上传对话框。

详情见