Rails: Rendering Partials through Ajax

后端 未结 3 943
轻奢々
轻奢々 2020-12-16 04:52

I have a page with tabs and I want to just render different partials through ajax when the tabs are clicked upon. I have some code but I don\'t think it is the most efficien

相关标签:
3条回答
  • 2020-12-16 05:29

    I'm using rails 4.2 and @prasvin answer pointed me in the right direction but when I used

    format.json { render :json => {:success => true, :html => (render_to_string 'instruments')} }
    

    I would get an error "Missing template ... instruments..."

    After some reading i found this comment rails render_to_string giving errors with partial view. @marcel mentioned you need to specify the file is a partial, partial: 'instruments', as below:

    format.json { render :json => {:success => true, :html => (render_to_string partial: 'instruments')} }
    
    0 讨论(0)
  • 2020-12-16 05:36

    See my answer to a previous post. This will give you an idea AJAX in Rails: Show model#new form after completing a model#update

    What you can do is render a json in the action and pass the partial as json.

    def mostrecent
      @school = School.find_by_slug(request.url.gsub('http://localhost:3000/','')).id
      @microposts = @user.microposts.order('created_at DESC').paginate(:per_page => 3, :page => params[:page])
      respond_to do |format|
        format.json { render :json => {:success => true, :html => (render_to_string 'users/microposts')} }
        format.html { }
      end
    end
    

    You can access the json in your js (i.e. a javascript/coffeescript file such as mostrecent.js or mostrecent.js.coffee) and replace the current element.

    $('.TabText').live 'ajax:success', (event,data) ->
      $('#ContentBody').html(data.html) if(data.success == true)
    
    0 讨论(0)
  • 2020-12-16 05:45

    Prasvin's answer is spot-on. Returning and executing JS may seem simple but it makes debugging much nastier - how do you set a breakpoint in JS that was returned via AJAX? Instead you should include all of your JS in the page and only send data back.

    0 讨论(0)
提交回复
热议问题