Rails Flash注意事项完成方法后通过Ajax

时间:2015-01-09 06:16:16

标签: javascript jquery ruby-on-rails ajax flash

当我的控制器成功完成上传文件时,我希望通过ajax将闪回通知发送回我的视图。但是,我不确切知道如何处理来自服务器的响应。我所拥有的是我认为非常接近我想要的东西,但它并不是很有效。任何帮助将不胜感激。谢谢!

我的控制器

def import
    begin
      Thread.new do
        Order.import(params[:file])
        ActiveRecord::Base.connection.close
      end
    rescue
      redirect_to root_url, notice: "Invalid CSV file format."
    end
    format.js { flash.now[:notice] = "Here is my flash notice" }
end

我的Ajax Javascript

$(function() {

  var bar = $('.bar');
  var percent = $('.percent');
  var status = $('#status');

  $('form').ajaxForm({
    beforeSend: function() {
      status.empty();
      var percentVal = '0%';
      bar.width(percentVal);
      percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
      var percentVal = percentComplete + '%';
      bar.width(percentVal);
      percent.html(percentVal);
    },
    complete: function(xhr) {
      status.html(xhr); //I think I need to change this but not sure what to
    }
  });
});

1 个答案:

答案 0 :(得分:0)

def import
    begin
      Thread.new do
        Order.import(params[:file])
        ActiveRecord::Base.connection.close
      end
    rescue
      redirect_to root_url, notice: "Invalid CSV file format."
    end
     @notice = "Here is my flash notice"
end

$(function() {

  var bar = $('.bar');
  var percent = $('.percent');
  var status = $('#status');

  $('form').ajaxForm({
    beforeSend: function() {
      status.empty();
      var percentVal = '0%';
      bar.width(percentVal);
      percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
      var percentVal = percentComplete + '%';
      bar.width(percentVal);
      percent.html(percentVal);
    },
    complete: function(response) {
       // replace the response in the div which displays notice
       status.html(response)
          }
  });
});