【发布时间】:2018-05-01 23:39:16
【问题描述】:
我无法让我的脚本多次运行window.location.replace。我有一个烧瓶应用程序,它根据从服务器上的流式访问日志中找到的唯一 ID 创建文件。一旦文件在服务器上,我有一个烧瓶路由,如果用户被重定向到https://somewebsite.com/getFile/<id>,它会将在服务器上创建的文件推送到客户端。
下面是我的脚本:
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
var response = '';
if(xhr.readyState === 4 && xhr.status === 200){
response = xhr.responseText;
response = response.substring(0, response.length-1);
response = response.split('\n');
for(x in response){
url_path = response[x];
window.location.replace(url_path);
};
};
};
xhr.open('GET', '{{ url_for('stream') }}', true);
xhr.send();
</script>
我调用了几个console.log() 来查看for 循环是否正确运行。即使是给window.location.replace 的url_path 也是正确的。需要注意的一点是,当重定向到https://somewebsite.com/getFile/<id> 时,浏览器在技术上不会更改为该 url 路径,因为flask 没有呈现模板,而是返回下载文件,因此浏览器停留在当前 url文件下载后的路径。
我不确定为什么我无法让脚本多次运行window.location.replace。似乎响应对象中有 2 个 url_path ,只有最后一个正在下载。 3 或 4 条路径也是如此。任何见解都会有所帮助。谢谢
【问题讨论】:
-
您可以尝试使用
window.location.assign而不是window.location.replace -
@LeoFarmer 感谢您的回复,我尝试使用
window.location.assign,但它仍然只下载一个文件。我检查了服务器日志,只看到一个 GET 请求,而另一个没有。正在执行。我在请求后添加了一个console.log,它会同时打印。
标签: javascript xml xmlhttprequest