2017-09-10 1 views
0

백그라운드에서 큰 보고서 파일을 생성해야합니다. 다음은 OrderReport 개체를 만드는 간단한보기입니다.레일 앱에서 컨트롤러에서 js로 ID를 전송하는 방법

<%= simple_form_for order_report, remote: true do |f| %> 
    <%= f.input :start_date, as: :date, html5: true %> 
    <%= f.input :end_date, as: :date, html5: true %> 
    <%= f.submit "Generate report", id: "test" %> 
<% end %> 

그리고 컨트롤러에 무슨 일이 일어나고 있는지 그 :

def create 
    order_report = OrderReport.new(order_report_params) 
    order_report.user = current_user 
    order_report.save 

    OrderReportJob.new(order_report).delay.perform 

    render nothing: true 
end 

사용자 후이 작업은 보고서를 생성하기 위해 백그라운드 프로세스를 생성하는 제출 버튼을 클릭합니다. 이 백그라운드 작업의 상태를 확인하기 위해 엔드 포인트를 썼습니다. 이 JS 이것이 JS 스크립트의 일부분

$.ajax({ 
     url: report_url, 
     success: function(report) { 
     if(report.status === 'progress') { 
      $("#spin").show(); 
      $interval = setInterval(checkStatus, 3000); 
     } 
     } 
    }); 

#test buttom의 ID로 등록하는 onclick 함수이다. 그것은 잘 작동하지만 마지막 단계는 생성 된 ID OrderReport을이 js 파일로 보냅니다. 당신은 JS 스크립트에서 볼 수 있듯이 내가 가지고 report_url 변수 - 이미 하드 코딩 및

var report_url = '/order_reports/1' 

그래서 주요 아이디어는 그것이 가능하다면, 생성 OrderReport의 ID를 잡으려고처럼 보이는, 그리고 JS에서 사용할 것 스크립트. 올바르게 전달하려면 어떻게해야합니까?

업데이트 :

def create 
    order_report = OrderReport.new(order_report_params) 
    order_report.user = current_user 

    respond_to do |format| 
    if order_report.save 
     OrderReportJob.new(order_report).delay.perform 
     format.json { head :created, location: order_report } 
    else 
     format.json { head :unprocessable_entity } 
    end 
    end 
end 

head :created, location: order_report가 반환 : 더 편안하고 솔루션 요청에 무슨 일이 있었는지 클라이언트에게 의미있는 응답 코드를 사용하는 것입니다

order_report.js

$(function() { 
    $('#test').click(function() { 
    var report_url = '/order_reports/39' 

    $.ajax({ 
     url: report_url, 
     success: function(report) { 
     if(report.status === 'progress') { 
      $interval = setInterval(checkStatus, 3000); 
     } 
     } 
    }); 

    function checkStatus() { 
     $.ajax({ 
     url: report_url, 
     success: function(report) { 
      if(report.status === 'done') { 
      clearInterval($interval) 
      } 
     } 
     }); 
    } 
    }); 
}); 
+0

당신이 json' 렌더링'시도하고 그 순간에 보고서의 ID를 전달 했습니까? –

답변

1

201 - Created 응답에 생성 된 리소스에 대한 URL이 포함 된 location 헤더가 포함되어 있습니다.

이것은 당신이 레일 UJS ajax:success and ajax:error events을 수신 할 수 있습니다 :

<%= simple_form_for order_report, remote: true, html: { class: 'order_report_form', 'data-type' => 'json'} do |f| %> 
    <%= f.input :start_date, as: :date, html5: true %> 
    <%= f.input :end_date, as: :date, html5: true %> 
    <%= f.submit "Generate report", id: "test" %> 
<% end %> 

$(document).on('ajax:success', '.order_report_form', function(e, data, status, xhr){ 
    function checkStatus(url) { 
    return $.getJSON(url).then(function(data) { 
     // some logic here to test if we have desired result 
     if (!desiredResult) { 
     // never use setInterval with ajax as it does not care 
     // if the previous request is done. 
     // instead use setTimeout with recursion 
     setTimeout(1000, function(){ checkStatus(url) }); 
     } else { 
     // do something awesome 
     } 
    } 
    } 
    checkStatus(xhr.getResponseHeader('location')); 
}); 

$(document).on('ajax:error', '.order_report_form', function(){ 
    alert("Oops"); 
}); 
+0

답장을 보내 주셔서 감사 드리며 위치가있는 헤더가 작동합니다. 그러나 나는 아직도 js에서 그 위치를 잡을 수 없다. 전체 js 파일로 응답을 업데이트하여 3 초 지연 상태를 확인했습니다. 내 U에 따라 UR 응답을 업데이트 할 수 있습니까? –

관련 문제