簡體   English   中英

在沒有Rails幫助器的Ajax調用后呈現部分內容(使用Webpack)

[英]Render partial after ajax call without rails helpers (using webpack)

show.html.erb頁面中,我有一個項目列表:

<div id="shopOffersPartial">
   <%= render "shops/shop_offers", offers: @offers %>
</div>

在局部中,僅存在一個循環。 @offers來自后端

<% offers.each do |offer| %>
  <%= render "shared/mini_offer_card/content", offer: offer, shop: @shop %>
<% end %>

我想在每個按鍵事件中過濾元素子。 為此,我聽了一個輸入。 我在Webpack中有JS邏輯。

const shopFilterProductsInput = document.getElementById("shopFilterProducts");
const shopId = shopFilterProductsInput.dataset.shopid;
const shopOffersPartial = document.getElementById("shopOffersPartial");

const filterOfferes = (e) => {
  let inputValue = shopFilterProductsInput.value;

  const url = `/shops/${shopId}?query=${inputValue}`;

  fetch(url)
  .then(function() {
    shopOffersPartial.innerHTML = "<%= render 'shops/shop_offers', offers: @offers %>";
  })
  .catch(function() {
      // This is where you run code if the server returns any errors
  });
}

if (shopFilterProductsInput) {
  shopFilterProductsInput.addEventListener("keyup", filterOffers)
}

我的問題在代碼的這一部分:

fetch(url)
  .then(function() {
    shopOffersPartial.innerHTML = "<%= render 'shops/shop_offers', offers: @offers %>";
  })

收到響應后,我想重新渲染具有項目列表的部分。

在rails中,使用.js.erb可以執行以下操作:

// app/views/reviews/create.js.erb
// Here you generate *JavaScript* that would be executed in the browser
function refreshForm(innerHTML) {
  const newReviewForm = document.getElementById('new_review');
  newReviewForm.innerHTML = innerHTML;
}

function addReview(reviewHTML) {
  const reviews = document.getElementById('reviews');
  reviews.insertAdjacentHTML('beforeend', reviewHTML);
}

<% if @review.errors.any? %>
  refreshForm('<%= j render "reviews/form", restaurant: @restaurant, review: @review %>');
<% else %>
  addReview('<%= j render "reviews/show", review: @review %>');
  refreshForm('<%= j render "reviews/form", restaurant: @restaurant, review: Review.new %>');
<% end %>

但是我在一個Webpack文件中。 我不能使用Rails助手。

然后如何使用Webpack渲染Rails助手?

這段代碼

  fetch(url)
  .then(function() {
    shopOffersPartial.innerHTML = "<%= render 'shops/shop_offers', offers: @offers %>";
  })

應替換為:

  fetch(url)
  .then(function(res) {
     return res.text();
  }).then(function(html) {
     shopOffersPartial.innerHTML = html;
  });

您不必在JS文件中使用render /shops/${shopId}?query=${inputValue}訪問的控制器應返回所需的html。 像這樣:

def show
  # offers = ???
  # ...
  respond_to do |format|
    format.html { render 'shops/show' }
    format.js { return plain: render_to_string("shops/shop_offers", offers: offers, layout: false) }
  end
end

暫無
暫無

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

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