无法执行AJAX请求渲染的js.erb代码,React-Rails交互问题咨询
Let's break down why your js.erb code isn't running and walk through solutions tailored to your React + Rails setup:
Why This Happens
In traditional Rails apps, js.erb templates are executed automatically by Turbo (or the old Rails UJS) when the server returns a JavaScript-formatted response. But since you're using Axios in a React SPA:
- Axios defaults to expecting a JSON response, so it treats the returned js.erb content as raw text data instead of executable code.
- There’s no Rails UJS/Turbo layer in your React flow to parse and run the JS automatically.
Solution 1: Make Axios Handle & Execute js.erb
If you need to keep using js.erb (e.g., you’re leveraging Rails view variables or have complex legacy JS), follow these steps:
1. Update Your Rails Controller
Ensure your update action explicitly responds with the JS format:
class MyController < ApplicationController skip_before_action :ensure_logged_in skip_before_action :authenticate_admin_user skip_before_action :verify_authenticity_token # Note: Add CSRF protection in production! def update # Your update logic here (e.g., find record, update attributes) @some_data = { message: "Update successful" } # Example variable for js.erb respond_to do |format| format.js # This will render app/views/my/update.js.erb end end end
2. Adjust Axios Request Headers
Tell Rails you accept a JavaScript response, not JSON:
// Get CSRF token from meta tag (re-enable this for production security!) const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content; axios.post(update_url, { bunch_of_data: data }, { headers: { 'Content-Type': 'application/json', 'Accept': 'text/javascript', // Critical: Request JS response 'X-CSRF-Token': csrfToken // Add back for production to prevent CSRF attacks } }) .then(res => { // Safely execute the returned JS code (avoid eval for better security!) const script = document.createElement('script'); script.textContent = res.data; document.body.appendChild(script); document.body.removeChild(script); // Clean up after execution }) .catch(err => console.error('Request failed:', err));
3. Validate Your js.erb Template
Make sure your update.js.erb contains valid JavaScript, using Rails ERB syntax to inject backend variables safely:
# app/views/my/update.js.erb console.log("js.erb code executed!"); // Inject backend variables with to_json to avoid syntax issues const serverData = <%= @some_data.to_json %>; alert(serverData.message);
Solution 2: Switch to JSON Responses (Recommended for SPAs)
For React SPAs, it’s cleaner to return JSON data and handle all frontend logic in React, instead of executing server-sent JS. Here's how:
1. Update Rails Controller to Return JSON
def update # Your update logic here success = true # Replace with actual success check from your code message = success ? "Updated successfully" : "Update failed" respond_to do |format| format.json { render json: { success: success, message: message } } end end
2. Handle Response in React
axios.post(update_url, { bunch_of_data: data }, { headers: { 'Content-Type': 'application/json' } }) .then(res => { const responseData = res.data; console.log(responseData.message); // Update React state or DOM here (e.g., show a success alert or refresh data) }) .catch(err => console.error('Update failed:', err));
Critical Security Note
You’ve skipped verify_authenticity_token—never leave this disabled in production. Add the CSRF token to your Axios headers (as shown in Solution 1) to protect against cross-site request forgery attacks.
内容的提问来源于stack exchange,提问作者lolcopter

