You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby on Rails 7中like.js.erb文件无法执行问题求助

Hey there, let's troubleshoot why your like.js.erb code isn't running even though your GET request is succeeding! The core issue here is that when you use a raw XMLHttpRequest like you are, the browser doesn't automatically execute the JavaScript it receives—it just gives you the text content. Here's how to fix this, plus a couple other things to check:

Fix 1: Manually execute the returned JavaScript in your Stimulus controller

Modify your XHR call to handle the response and run the script. The safest way is to create a script element and inject it into the page (instead of using eval, which carries security risks if you're dealing with untrusted content):

import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
  connect() {
    this.element.addEventListener("click", (e) => {
      const post_id = e.target.getAttribute("data-id")
      console.log(post_id)
      const oReq = new XMLHttpRequest();
      oReq.open("GET", "/post/like/" + post_id)
      
      // Add this onload handler to execute the returned JS
      oReq.onload = () => {
        if (oReq.status === 200) {
          const script = document.createElement('script');
          script.textContent = oReq.responseText;
          document.body.appendChild(script);
          // Clean up the script tag after it runs
          document.body.removeChild(script);
        }
      }
      
      oReq.send()
    })
  }
}

Fix 2: Use Rails UJS for automatic JS handling (simpler approach)

Instead of writing raw XHR, leverage Rails' built-in UJS (Unobtrusive JavaScript) to handle the request and script execution automatically. This is the more "Rails-native" way to do it:

  1. First, make sure UJS is set up in your app (if you're using Rails 7+, you might need to import @rails/ujs in your JavaScript entry file).
  2. Replace your manual click handler with a link_to or button_to that includes remote: true:
<%# In your post view %>
<%= button_to "Like", post_like_path(post), remote: true, method: :get, data: { id: post.id } %>

With this setup, Rails will automatically send the AJAX request, receive the like.js.erb response, and execute the JavaScript for you—no need for custom XHR code.

Quick Checks to Verify

  • Confirm the response header: In your browser's DevTools (Network tab), check that the response for /post/like/:post_id has a Content-Type header set to application/javascript. Rails should handle this automatically when using format.js, but it's worth verifying.
  • Check for syntax errors: Make sure your like.js.erb has no typos (your console.log("hello") looks fine, but if you add ERB logic later, double-check that it's valid).
  • Verify your route: Ensure your routes.rb has the correct route defined, like:
    get '/post/like/:post_id', to: 'likes#save_like', as: :post_like
    

Once you implement one of these fixes, your console.log("hello") should run as expected when you click the like button!

内容的提问来源于stack exchange,提问作者Kyowan Kim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 06:54:31