![](/img/trans.png)
[英]ActionController::UnknownFormat with respond_to js in Action:Create
[英]ActionController::UnknownFormat with respond_to js for AJAX
我正在互聯網上搜索有關此主題的信息,但是我不了解AJAX如何與rails一起使用,我已經檢查了文檔,只是根本不了解它。
我所知道的是AJAX是異步的,只需要將以下代碼放在視圖中即可發出請求:“ remote:true
”,我不明白的重要之處在於此代碼:
respond_to :js
顯然,它告訴控制器它將響應Javascript,並且您必須為要使用JS做的任何事情制作一個文件,我項目的結構是這樣的:
視圖
New.html.erb:
<p>Imagen de portada</p>
<%= simple_form_for @entries, remote: true do |f| %>
<% f.file_field 'input-image' %>
<% end %>
<div id="image-entry"></div>
查看路線:
views | -->admins | -->entries |-->new.html.erb |-->new.js.erb
控制者
entry_controller.rb
module Admins
class EntriesController < ApplicationController
before_action :authenticate_admin!
def index
render 'index'
end
def new
@entries=''
render 'new'
respond_to :js
end
end
end
控制器路線:
controllers | -->admins | -->entries_controller.erb
JS
new.js.erb
console.log('funciona');
$('#input-image').click(function(){
$('body').css('background-color', 'red');
});
JS路線:
views | -->admins | -->entries |-->new.html.erb |-->new.js.erb
錯誤
我在此代碼中的錯誤如下:
ActionController::UnknownFormat
因此,我對此問題有疑問,並且在JS中文件的正確名稱是什么才能使respond_to
正常工作。
Irfan Fadilah在Facebook上的回答:
EntriesController中的“ new”方法未處理您的請求。 默認的表單方法是POST,因此Rails會在您的EntriesController中尋找“創建”方法。
您可以閱讀Rails Guide中的RESTful路由以了解更多詳細信息。
為了使您的AJAX請求起作用。 在視圖/條目中在EntriesController中添加“ create”方法,然后在視圖/條目中創建create.js.erb(只需編寫alert(“ Hello”);或對其進行測試)。
https://www.facebook.com/groups/railsrocks/permalink/10151091424934957/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.