在rails视图中发出Javascript循环请求

Making a Javascript Loop request in rails view

本文关键字:Javascript 循环 请求 rails 视图      更新时间:2023-09-26

我需要从给定的链接下载一个文件。为了做到这一点,我必须对该链接提出get请求。它可以有三种状态:
1.代码为200,一旦请求落地,将开始下载
2.代码202,这意味着我必须重复请求,因为文件正在上传
3.错误代码,我必须创建一个显示这一点的dom元素。

工作原理:
我向这个轨道行动提出请求:

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视图中。我设法编写的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);
        }

如果状态为202,则CCD_ 1是再次进行请求的地方。