我需要从给定的链接下载文件。为了做到这一点,我必须向该链接发出获取请求。它可以有 3 种状态:
1. 代码200,请求到达后将开始下载
2. 代码 202 意味着我必须重复请求,因为文件正在上传
3. 错误代码,我必须创建一个 dom 元素来显示该错误代码。
工作原理:
我向这个 Rails 操作提出请求:
def by_month
export_form = Commissions::ByMonthForm.new(current_user)
if export_form.submit(params)
@export = export_form.export
else
show_errors export_form.errors
end
end
这又会开始文件上传。我不知道它什么时候准备好(取决于文件有多大)。现在我必须创建一个对链接的 javascript get 请求,该请求遵循我在帖子开头给出的指示。并将其集成到 Rails 的 by_month.html.erb View 中。我设法编写的 JavaScript 是:
function httpGetAsync(theUrl){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
redirect_to_main();
}
else if(xmlHttp.status == 202) {
httpGetAsync(theUrl);
}
else {
make_error_css();
}
}
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
但是我认为这不起作用。我有什么想法可以做到这一点吗?(redirect_to_main 和 make_error_css 是我稍后将自己实现的函数)。
最佳答案
更新根据下面的评论
你能试试这个吗
function httpGetAsync(theUrl){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
redirect_to_main();
}
else if(xmlHttp.status == 202) {
setTimeout(
makeRequest(theUrl),
3000);
}
else {
make_error_css();
}
}
}
//makeRequest(xmlHttp, theUrl);
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
function makeRequest(theUrl){
httpGetAsync(theUrl);
}
makeRequest()
是在状态为 202 时再次发出请求的位置。
关于javascript - 在 Rails View 中发出 Javascript Loop 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34513011/