【发布时间】:2015-02-15 16:11:18
【问题描述】:
我正在尝试使用 ajax 渲染部分,但由于某种原因它返回此错误:
ActionController::UnknownFormat in ThingsController#upvoterandom
ActionController::UnknownFormat
我很困惑,因为我以前用基本相同的格式完成了一些事情,而且我从来没有遇到过任何问题。有人看到我的代码有什么问题吗?我可以用 ajax 渲染一个字符串;只有当我尝试渲染部分时,我才会收到错误。顺便说一句,我通过删除format.html这一行然后直接在我的浏览器中访问upvoterandom_thing路径实现了这个错误。
views/things/show.html.erb
<div id= "randomajax" >
<div id="randajax">
<%= link_to @rand.name, thing_path(@rand) %>
<%= link_to image_tag("UpArrowGray.jpg", class: "rand_up_vote"), remote: true, %>
<script type="text/javascript">
function reload_script() {
$(".rand_up_vote").click(function () {
$.get( "<%= upvoterandom_thing_path(:id => @rand.id) %>", function( data ) {
});
});
}
reload_script();
</script>
</div>
</div>
controllers/things_controller.rb我在错误突出显示的行周围加上了星号。
def upvoterandom
@thing = Thing.find(params[:id])
#...
***respond_to do |format|***
format.html { redirect_to root_path }
format.js
end
end
views/things/upvoterandom.js.erb: .html("test") 返回“test”,所以问题一定出在渲染上。
$('#randomajax').html("<%= j(render(@randajax)) %>");
views/things/_randajax.html.erb
TEST
这是另一种几乎相同的 AJAX 结构:
views/things/show.html.erb
<%= form_for([@thing, @comment], remote: true) do |f| %>
<%= f.text_area :text %>
<%= f.submit "Post", id: "postacomment" %>
<% end %>
controllers/cmets_controller.rb
def create
@thing = Thing.find(params[:thing_id])
@comment = @thing.comments.create(comment_params)
respond_to do |format|
format.html { redirect_to root_path }
format.js
end
end
views/cmets/create.js.erb
$('#comments_h2').prepend("<%= j(render(@comment)) %>");
views/cmets/_comment.html.erb
TEST
【问题讨论】:
标签: javascript ruby-on-rails ruby ajax ruby-on-rails-4