weixin_33705053 2014-04-26 01:43 采纳率: 0%
浏览 27

Rails AJAX快捷方式?

Using remote:true on a form, or something, and responding from the controller with :js, we can tell rails to execute some javascript file.

If you're destroying a user, for example. You'd have the User controller, and the Destroy action. You'd then have a file views/users/destroy.js.erb with something along the lines of:

$("ul#users").html("<%= j render partial: 'user_list' %>");

My question is... Is there a shortcut to just put that javascript in the controller, so that I don't have to have these tiny files littered about my app? If I'm only rendering a partial with some instance variables, and nothing else, I'd like to see something like:

respond_with render :js, with: 'partial_foo', on: '#selector .bar'

Is there such a shortcut?

  • 写回答

1条回答 默认 最新

  • weixin_33709609 2014-04-26 12:47
    关注

    The only shortcut I could recommend for you is to use json and handle the response with your unobtrusive JS:

    #view
    <%= form_for @variable, remote: :true, method: :json %>
    
    #controller
    respond_to :json, :html
    
    def action
        respond_with @variable
    end
    

    JSON sends small serialized data objects, meaning you won't have to handle any files, and can handle the data as required:

    #app/assets/javascripts/application.js
    $(element).on("ajax:success", function(data) {
        message = JSON.stringify(data);
        alert(message.attribute);
    });
    

    If you like this idea, I can come back with some ideas for handling the partial

    评论

报告相同问题?