简体   繁体   中英

Ruby on Rails + Ajax

I am trying to update a div in my rails application. Iam just learning ROR. So Its a learning stage for me.Please find the code. In view page...

<%= javascript_tag do %>
     jQuery(function($) 
{

     $("#tabs4").click(function()
     {      
        $.ajax(
        {
        url:'/spaces/showcal',
        type:'GET'

        });
      });

});


<% end %>

In spaces controller..

def showcal

    respond_to do |format|

     format.html 
     {
      render (:update) { |page|
      page.replace_html 'tab4', :partial => 'spaces/showcal'
    }}
    end
end

What am I doing wrong here.. Please help I also have a partials page (_showcal)which has some text to display into that div.

You should request /spaces/showcal.js and react to format.js .

I never worked with $.ajax , you might need to set additional parameters there. With script.aculo.us, something like this works:

new Ajax.Request('/tasks/#{task.id}.js',
    {asynchronous:true, evalScripts:true, method:'get'});

When using ajax, a good way to debug this kind of thing is see what response the server returns. If it looks good, then you know your javascript code needs to change to get it working, if it looks wrong, then fix the server side code first.

Here's how i would do it:

def showcal
  render :layout => false
end


#showcal.html.erb
<%= render :partial => "spaces/showcal" %>

Your js block:

jQuery(function($) 
{
  $("#tabs4").click(function()
    {      
      $.ajax({
        url:'/spaces/showcal',
        type:'GET',
        success: function(data)
        {
          $('#tab4').html(data);
        }
      });
    });
});

I generally prefer using javascript as supposed to rails built in code when it comes to replacing and using content with ajax. I have to admit, because of this, I'm not sure if your update action was mostly correct or not. The page.replace_html should work if you're using the prototype helpers. The only thing is because you are doing an ajax request to achieve it and the resulting body would contain that code, and it would not execute on your current dom. So i think that was probably executing, but because it's on a separate page response, it didnt do anything.

Give my suggestions a try, and let me know how it goes. Sorry that my answer is a bit hazy.

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