簡體   English   中英

Ajax 加載靜態 Rails 部分

[英]Ajax Load Static Rails Partial

在我的 rails 應用程序中,我有一個 html 模板位於public/templates/_hero-1.html.erb

在我application.js.erb文件,我想該模板加載到div我動態創建的,之前我渲染整個div

// Append component to text editor when clicked
$('.js-TemplateThumbnail').click(function() {
    // Define new template container
    var newTemplateContainer = $('<div class="position-relative hideChild js-TemplateContainer">');

    // Insert selected template into new template container
    newTemplateContainer.load("<%= 'public/templates/hero-1' %>");

    // Build new template
    $('.js-Canvas .js-TemplateContainer').last().after(newTemplateContainer);
});

但我收到控制台錯誤GET http://localhost:3000/public/templates/hero-1 404 (Not Found)

快速答案/相關 SO 答案: 在 js.erb 文件中渲染部分

更長的答案:有幾種方法可以做到這一點。 你可以試試:

newTemplateContainer.load("<%= 'render partial: public/templates/hero-1' %>");

不是積極的,會起作用。 這對我來說感覺很糟糕,並且還會給您留下高度耦合的代碼。 如果該模板的名稱發生更改,則必須在 n 個位置更新它。

我會解耦 JS 並在config/routes.rb創建一個內部端點; 例如:

get templates/:id

然后,

class TemplatesController < ApplicationController
  def show
    @template = Template.find(params[:id])
  end   
end

然后在單擊處理程序內的 JS 中,您可以:

$.get('/templates/hero-1', function(data) {
   // do stuff with returned data
   $('.js-Canvas').html(data)
});

非常簡單,但更多的是試圖概述一種不同的方法。 這似乎也是車把可以提供幫助的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM