呈现部分视图时在ajax中动态内容 [英] dynamic content in ajax while rendering partial views

查看:70
本文介绍了呈现部分视图时在ajax中动态内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户单击不同的链接时,如何获得动态内容?

How do I get dynamic content when user clicks on different links?

views/dashboard/index.html.haml

.container
  - @trips.each do |trip|
    = link_to trip.id, quick_view_trips_path, remote: true

我很确定 quick_view_trips_path 是不正确的,因为所有链接都是这样:

I'm pretty sure the quick_view_trips_path is incorrect as all the links are this:

<a href="/trips/quick_view">1</a>
<a href="/trips/quick_view">13</a>
<a href="/trips/quick_view">51</a>

我需要以某种方式使这些链接动态化,然后当用户单击它时,模式窗口也将是动态的.

Somehow I need to make these links dynamic, and then when user clicks on it, the modal window would be dynamic too.

如果我仅用 trip

= link_to trip.id, trip, remote: true

什么也没有发生,并且url更改为正确的url,但是我的模态窗口没有通过ajax呈现.以下是该网址现在的示例:

Nothing happens, and the url changes to the correct url, but my modal window doesn't get rendered through ajax. Here's an example of what the url looks like now:

<a href="/trips/slug-title-url-correct">1</a>

除了我要使用动态内容完成的工作外,还有没有办法像这样更改我的网址:

In addition to what I'm trying to accomplish with dynamic content, is there a way to maybe change my url like so:

<a href="/trips/slug-title-url-correct?quick_view=on">1</a>

是否可以在URL末尾附加?quick_view = on 并使所有内容重新正常工作?

Is it possible to get ?quick_view=on appending to end of URL and make everything work again?

这是我其余的代码:

views/trips/quick_view.js.erb

$('body').append('<%= j render partial: "trips/quick_view" %>');

views/trips/_quick_view.html.haml

.root-container
  = @trip.title
  = @trip.image
  = @trip.more_details

现在这也不起作用,因为我的应用程序返回了未定义的方法

This doesn't work either right now, as my application returns undefined method

routes.rb

resources :trips do
  collection do
    get 'quick_view'
  end
end

trips_controller.rb

def quick_view
  respond_to do |format|
    format.html # quick_view.html.erb
    format.js # quick_view.js.erb
    format.json { render json: @trip }
  end
end

我是否还需要向此控制器添加任何内容,以确保将通过部分生成正确的内容?

Do I need to add anything to this controller as well to ensure the correct content will be generated through the partial?

推荐答案

这种方式如何

  1. 路径

link_to trip.id, quick_view_trips_path(:js, trip_id: trip.id), remote: true

这将呈现< a href ="/trips/quick_view.js?trip_id = 1"> 1</a>

控制器

def quick_view
  @trip = Trip.find(params[:trip_id])
  respond_to do |format|
    format.html # quick_view.html.erb
    format.js # quick_view.js.erb
    format.json { render json: @trip }
  end
end

它将响应 views/trips/quick_view.js.erb 文件

这篇关于呈现部分视图时在ajax中动态内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆