Ajax加载静态Rails部分

Ajax Load Static Rails Partial

本文关键字:部分 Rails 静态 加载 Ajax      更新时间:2023-09-26

在我的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的click处理程序中,你可以:

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

非常简单,但更重要的是试图概述一种不同的方法。这似乎也是把手可以帮助的事情。