在Rails 4中处理AJAX调用(成功,错误,发送前,完成)

3

我希望了解在Rails 4中处理ajax调用的正确方式(使用remote:true选项),问题在于我希望在处理过程中使用所有经典步骤,如success、error、beforeSend和complete。

假设我有一个按钮,它会加载一个带有ajax内容的模态窗口:

视图(products/index):

<%= link_to('Order this', new_order_path(product: product), remote: true) %> 

订单控制器:

  def new
        @order = Order.new
        @product = Product.find(params[:product])

        respond_to do |format|
          format.html
          format.js
        end
      end

new.js.erb:

(function(){
  var $modalWindow = ...
  // some code that loads the modal window and closes it

  $modalWindow.html("<%= j render('form') %>"); // puts the needed product form 
                                                   into my modal window
}());

这段代码可以正常工作,但是 before/after/success/error 的输出结果在哪里呢?

接下来,当用户点击“订购产品”按钮时,我的订单控制器中有以下代码:

def create
    @product = Product.find_by(params[:id])
    @order = current_office.orders.build(order_params)

    respond_to do |format|
      if @order.save

        format.html { 
          flash[:success] = 'Order created'
          redirect_to products_url
        }
        format.js
      else
        render :new
        format.html { render :new }
        format.js   { render :js=>'alert("ajax error");' }
      end
    end
  end

当单击“创建”按钮时,如何进行处理?我的create.js.erb仅关闭模态窗口,但我希望它完全处理请求,显示预加载程序beforeSend,然后是成功/错误,最后才关闭。

希望不要太混乱!

1个回答

2
这段代码中 before/after/success/error 事件应该放在哪里?
这些 ajax 事件不应该放在这段代码中,因为它们无法绑定到原始的 DOM 元素上。你需要将它们放在原始的 JS 中,只有这样才能将这些元素绑定到发送请求的 DOM 元素上。
#app/assets/javascripts/application.js
$(document).on("ajax:success", "#element", function() {
    //do something
});

这里有一个不错的资源供您参考:rails3 rails.js and jquery catching success and failure of ajax requests
后端:
如果你要处理后端的处理代码,你需要使用某种验证来确定应该发生什么:
 #app/controllers/orders_controller.rb
 def new
    @order = Order.new
    @product = Product.find(params[:product])

    respond_to do |format|
      format.html
      format.js { @state = "success" }
    end
  end

#app/views/orders/new.js.erb
(function(){
  <% if @state && @state == "success" %>
      var $modalWindow = ...
          $modalWindow.html("<%= j render('form') %>");
  <% else %>
      alert ("not successful");
  <% end %>
}());

前端:
如果您想在前端处理ajax请求,最好这样做:
#app/assets/javascripts/application.js
$(document).on("ajax:success", "#element", function(){
    //do something
});

插件
我目前还没有任何文档:
(function( $ ){        

   $.fn.leanModal = function(options) {

        //Defaults
        var defaults = {
            overlay: 0.5,
            overlay_color: "#000",
            closeButton: null,
            delay: null,
            drag: ".modal_title",
            removeModal: null,
            autoLoad: null,
            ajax: false
        };

        //Definitions
        var xhr;
        var plugin = this;
        var options = $.extend(defaults, options);

        //Init
        plugin.init = function() {

            if(options.autoLoad){
                $.extend(options, {modal_id: $(this)});
                create();
            }else{
                return this.each(function() {
                    $(this).click(function(e) {
                        e.preventDefault();
                        var href = $(this).attr("href");
                        var image = CheckImg(href);

                        var random = Math.floor(Math.random()*90000) + 10000;
                        var extras = (options.ajax || image) ? {modal_id: "#modal_" + random, ajax: href.replace(/\/$/, '')} : {modal_id: href};

                        $.extend(options, extras);
                        create();
                    });
                }); 
            }
        }

        //////////////////
        //    Actions   //
        //////////////////

        //Build
        var create = function() {
            if(options.ajax){

                //Loading
                load();

                //Image
                switch (true) {
                    case CheckImg(options.ajax):
                        append("img", options.modal_id.substring(1), options.ajax);
                        show();
                        break;
                    default:
                        fetch(options.ajax, function(data){
                            append("modal", options.modal_id.substring(1), options.ajax, data);
                            show();
                        }, function(xhr, text_status, error_thrown){
                            load();
                            alert("Sorry, there was an error!");
                        });
                        break;
                }

            }else{
                show();
            }
        }

        //Ajax
        var fetch = function(link, success, error) {
            xhr = 
            $.ajax({
                url: link,
                success: function(data) { success(data); },
                error: function(data)   { error(data); }
            });
        }

        //Overlay
        var olay = function(modal_id, removeModal, closeButton, ajax) {
            var overlay = document.createElement("div");
                overlay.setAttribute("id", "lean_overlay");

            document.body.appendChild(overlay);
            overlay.onclick = function() { close(modal_id, removeModal, $(closeButton), ajax); return false; };
        }

        //Show
        var show = function() {

            /* Vars */
            var id          = options.modal_id
            var removeModal = options.removeModal
            var closeButton = options.closeButton
            var drag        = options.drag
            var ajax        = options.ajax
            var opacity     = options.overlay

            /* Overlay */
            olay(id, removeModal, closeButton, ajax);

            /* Elements */
            var modal       = $(id);
            var overlay     = $("#lean_overlay");

            /* Display */
            var disp        = "test";

            /* Options */
            if (closeButton) {
                $(closeButton).css("z-index", "900");
                $(closeButton).on("click", function (e) {
                    e.preventDefault();
                    close(id, removeModal, $(closeButton));
                    return false;
                });
            }

            /* Load */
            if (ajax) {
                modal.waitUntilExists(function() {
                    load();
                    display($("#lean_overlay"), options.overlay_color, $(options.modal_id), options.overlay, options.drag);
                })
            } else { display($("#lean_overlay"), options.overlay_color, $(options.modal_id), options.modal, options.overlay, options.drag); }
        }

        //Close
        var close = function(modal, removeModal, closeButton, ajax) {

            /* Ajax */
            if(ajax){
                if (xhr) { xhr.abort(); }
                load(true);
            }

            /* Overlay */
            $("#lean_overlay").fadeOut(150, function(){
                $(this).remove();
                if(closeButton) {
                    closeButton.off("click");
                    closeButton.removeAttr('style');
                }
            });

            /* Modal */
            $(modal).fadeOut(150, function(){
                if (removeModal) {
                    $(this).remove();
                 }
            });

        }

        //Go
        plugin.init();
   }; 


    //////////////////
    // Dependencies //
    //////////////////

    //Image?
    var CheckImg   = function(url) { if(url) { return(url.match(/\.(jpeg|jpg|gif|png)/) != null); }}

    //Create
    var append     = function(type, id, src, data) {

        //Definitions
        var style = element = type;

        if (type == "modal") {
            var style = "ajax";
            var element = "div";
        }

        //Element
        var el = document.createElement(element);
            el.setAttribute("id", id);
            el.setAttribute("src", src);
            el.className = 'modal ' + style;

        //Ajax
        if (data) { el.innerHTML = data; }

        //Append
        document.body.appendChild(el);
    }

    //Show
    var display = function(overlay, overlay_color, modal, opacity, drag)    {

        /* Styling */
        overlay.css({
            "display": "block",
            "background": overlay_color,
            opacity: 0
        });
        modal.css({
            "display": "block",
            "position": "fixed",
            "opacity": 0,
            "z-index": 10200,
            "left": 0,
            "right": 0,
            "top": 0,
            "bottom": 0,
            "margin": "auto"
        });

        /* Init */
        overlay.fadeTo(150, opacity);
        modal.fadeTo(200, 1);
        if(drag.length > 0) { modal.draggable({ handle: drag }); }

    }

    //Ajax Load
    var load  = function(close) {
        if (close) { $(document).ajax_load({close: true});  } else {  $(document).ajax_load(); }
    }

})( jQuery );

用法。
#app/assets/javascripts/application.js
var load = function() {
    $('a[rel*=LeanModal]').leanModal({
        overlay: 0.9,
        removeModal: true,
        closeButton: ".title .close"
        ajax: true,
        drag: ".title"
    });
}
$(document).on("ready page:load", load);

#app/assets/sytlesheets/application.css.sass
/Overlay
#lean_overlay
position: fixed
z-index: 1500
top: 0px
left: 0px
height: 100%
width: 100%
display: none

&:hover
    cursor: pointer

 // Modal
 .modal
    //styling here


#app/views/application/index.html.erb
<%= link_to "test_ajax", ajax_path, rel: "LeanModal" %>

#app/controllers/application_controller.rb
layout Proc.new {|controller| controller.request.xhr? ? false : "application" }

这是一个很好的答案,非常感谢。我能看到 $(document).on("ajax:success"... 的一个问题是,如果我执行多个不同的 ajax 操作,我的应用程序对每个操作的反应都将是相同的? - The Whiz of Oz
1
谢谢!关于 $(document) -- 如果您委托给发起请求的元素,则不需要使用它 - https://learn.jquery.com/events/event-delegation/ - Richard Peck
谢谢。目前我认为将Ruby代码与JS混合可能是一种不好的做法,特别是在未来。我可能只会使用JavaScript并通过经典的方式(通过好老的$.ajax)完成工作。 - The Whiz of Oz
1
这取决于你想要实现什么。如果你想要加载一个模态框,我们实际上已经基于leanmodal制作了一个Ajax启用的模态框。如果你需要的话我可以分享代码?它基本上允许你调用视图,插件会处理剩下的部分。 - Richard Peck
我在谈论通常的应用程序ajax化,但是是的,很想看看你的插件并学习一些东西。 - The Whiz of Oz
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接