Ideas on simple 'Hello World' Rails-Ajax Example?
Learning/re-learning ajax using rails. I think rails-ajax has changed a lot in last few years so have not found a very simple 'Hello World' type ajax example (w/o resources, w/o records).
This is an attempt (below) at a simple rails ajax example based on references 开发者_Go百科I could find. It works -- however, it seems a bit cumbersome (ie one-to-one .js file to ajax request action). Does anyone have thoughts on an improved (more elegant) rails ajax 'Hello World'?
---------------------
View - 'edit.html.erb'
<div id="div_msg">
<%= link_to "Wow",
{:controller=>"rectangle_set_model" , :action=>'ajax_msg' , :id=>'1'},
:remote => true,
:class => 'link1',
:update => "div_hello",
:id => 'link1'
%>
</div>
<div id="div_hello">
</div>
---------------------
Controller - 'rectangle_set_model_controller.rb'
def ajax_msg
@msg1 = "Buenos Dias!"
respond_to do
|format|
format.html
format.js
format.xml
end
end
---------------------
Javascript (corresponding to ajax_msg format.js in controller)
- 'ajax_msg.js'
$('#div_hello').html("<%= controller.msg1 %>");
---------------------
Why do you have to render a JS view ?
Just use UJS and a standard Ajax call. You Rails action can render JSON :
format.js { render :json => { :text => "Hello the world" } }
// application.js
// jQuery
// in $(document).ready(function()...) or $("#my_button").click(function()...)
//
$.ajax({
url: "/home/hello",
success: function(response) {
$("#div_hello").html(response.text);
}
});
Thanks guys
Samuel - not quite working for some reason
Whenever I enable this line
format.js {render :json => { :text => "Hello the world" }}
I then get error in browser (on action link)
browser popup error --------> Expected ';'
is
精彩评论