简体   繁体   中英

Rails & AJAX, is there a reason you shouldn't render html view directly in controller action for ajax to process?

The classic way to work with Rails & Ajax is always something that looks like this:

// JS - let's assume this submits to dummies#create
$(form).submit()

# Dummies Controller
def create
   @dummy = Dummy.new(dummy_params)
   respond_to do |format| 
     format.js
   end
end

# /views/dummies/create.js.erb
$("page").append("<%= escape_javascript(render partial: 'dummy_view' ) %>"); 

# /views/dummies/_dummy_view.html
<h1><%= @dummy.name %></h1>

I've always been curious, because the above seems to create a random create.js.erb file with very little meat... is there a reason (eg, it's terrible convention, or terribly insecure or whatever), why you should NOT instead just render the view directly back to ajax?

// JS - basically takes responsibilites of create.js and puts it into the always
$.ajax(...).always(function(xhr, status){
    $("page").append($(xhr['responseText']))
    // responseText contains the partial rendered by the controller action
})

# Dummies Controller
def create
   @dummy = Dummy.new(dummy_params)
   render partial: 'dummy_view'
end

# /views/dummies/_dummy_view.html
# unchanged
<h1><%= @dummy.name %></h1>

NOTE above is pseudo-code, apologies for minor errors. The conceptual idea & question remain unchanged, though.

The create.js.erb is not random, is the view for the action with the expected format.

Generally, you may not have a view so simple (You may have different selectors other than "page", you may have some extra js code to be executed after or before the append), a js view/script is the general solution for an ajax request to give the response full control over what to do.

You could have what you want, but it will just work for your particular case when the selector is always "page" and you only want to append html to that element. Nothing prevents you from doing that (though you might want to use a custom ajax request and not rails' one since it sets js format by default and executes the response's script).

The convention is that a rails' remote request renders a js script, you can move out of the convention if you want. You'll lose a lot of flexibility with your approach as is (like... what if the create action fails an you need to display errors?).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM