可以在Rails 5视图中使用ajax请求呈现部分吗?

时间:2021-10-24 07:51:44

I have a view with some information and a render partial: 'path/to/partial'

我有一个视图,有一些信息和渲染部分:'path/to/partial'

I want to do something like render url: another_model_path(@model), remote: true.

我想做一些事情,比如呈现url: another_model_path(@model), remote: true。

I could partially accomplish what I wanted with link_to 'Load what I want', another_model_path(@model), remote: true

我可以使用link_to“加载我想要的”、another_model_path(@model)、remote: true来部分实现我想要的

However, I'd need to click the button to load the content I want. Is there anyway to do this without clicking any button and preferably not using custom javascript (just something like remote: true)

但是,我需要点击按钮来加载我想要的内容。如果不点击任何按钮,最好不使用定制的javascript(就像remote: true)

I saw that it is possible to add data-remote=true to any element, and Rails will take care of making the ajax request (as long as you also provide data-url='your_url'). I tried this in a but it didn't work. I tried it in a check_box_tag and it works, but again, I would need to click the checkbox )=

我看到可以向任何元素添加data-remote=true, Rails将负责发出ajax请求(只要您还提供data-url='your_url')。我试过了,但是没用。我在check_box_tag中尝试过它,它可以工作,但是同样,我需要单击复选框)=

Thanks in advance.

提前谢谢。

1 个解决方案

#1


2  

Well, I found a non-ideal solution here. Basically just use js to fire a request to the controller I want like:

我找到了一个非理想解。基本上就是使用js向我想要的控制器发出请求:

in the view:

在视图:

.some-class{ data: { remote="true", url: my_path(@model), method: :get } }
  .loading= fa_icon "spinner pulse", class: "fa-5x"

and in the .js:

和. js:

$ ->
  elem = $("div").find("[data-remote]")
  path = elem.data("url")
  method = elem.data("method") || "GET"
  defaultContent = elem.contents()

  elem.bind 'ajax:beforeSend', ->
    $(this).prepend(defaultContent)
    $(this).contents().css("opacity", "0.5")

  $.ajax({
    url: path,
    dataType: 'script',
    type: method,
    complete: ->
      defaultContent.remove()
  })

#1


2  

Well, I found a non-ideal solution here. Basically just use js to fire a request to the controller I want like:

我找到了一个非理想解。基本上就是使用js向我想要的控制器发出请求:

in the view:

在视图:

.some-class{ data: { remote="true", url: my_path(@model), method: :get } }
  .loading= fa_icon "spinner pulse", class: "fa-5x"

and in the .js:

和. js:

$ ->
  elem = $("div").find("[data-remote]")
  path = elem.data("url")
  method = elem.data("method") || "GET"
  defaultContent = elem.contents()

  elem.bind 'ajax:beforeSend', ->
    $(this).prepend(defaultContent)
    $(this).contents().css("opacity", "0.5")

  $.ajax({
    url: path,
    dataType: 'script',
    type: method,
    complete: ->
      defaultContent.remove()
  })