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:
- First, make sure UJS is set up in your app (if you're using Rails 7+, you might need to import
@rails/ujsin your JavaScript entry file). - Replace your manual click handler with a
link_toorbutton_tothat includesremote: 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_idhas aContent-Typeheader set toapplication/javascript. Rails should handle this automatically when usingformat.js, but it's worth verifying. - Check for syntax errors: Make sure your
like.js.erbhas no typos (yourconsole.log("hello")looks fine, but if you add ERB logic later, double-check that it's valid). - Verify your route: Ensure your
routes.rbhas 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

