我有一个标记为:remote => true
的链接,它向Controller#show as JS
发出请求并在浏览器中呈现。此请求完成后,将处理另一个Controller#show as HTML
的获取请求。
调试时我将节目动作内容包装在if request.xhr? && !request.format.html?
第一个Controller#show as js
请求在浏览器中显示正确,Controller#show as HTML
的意外呈现失败,显然没有任何内容显示在浏览器中。
我的问题是,有没有人在js通话后经历过这个后续的html通话?我在代码中找不到任何导致此问题的内容。
链接代码
= link_to article.name, blog_path(article.name.downcase.gsub(' ','-')), :remote => true
控制器代码
def show
article_name = params[:id].gsub('-',' ')
@article = Article.find_by_name(article_name)
respond_to do |format|
format.html # show.html.erb
format.js
format.xml { render :xml => @article }
end
end
show.js.haml代码
$('#content_index.blog').html("#{escape_javascript(render('article'))}");
_article.html.haml代码
.blog_post
%h2
= @article.name
%img{:src => "#"}/
.blog_text
%p
= @article.content
%center
.blog_post_bottom
#next.blogbuttons next
#previous.blogbuttons previous
%p
posted on
= link_to @article.created_at.to_s(:date_only), "#"
in
%a{:href => "#"} CS at work
by
= link_to @article.author_name, "#"
routes.rb代码
resources :articles, :only => [:index, :show]
resources :blog, :controller => :articles
来自单个js请求的日志输出(对于在禁用浏览器时使用javascript的html请求也会发生)
Started GET "/blog" for 127.0.0.1 at Thu Nov 03 14:38:29 -0400 2011
Processing by ArticlesController#index as JS
Article Load (9.3ms) SELECT `articles`.* FROM `articles`
Rendered articles/_articles.html.haml (2.3ms)
Rendered articles/index.js.haml (2.8ms)
Completed 200 OK in 20ms (Views: 3.5ms | ActiveRecord: 9.3ms)
Started GET "/blog" for 127.0.0.1 at Thu Nov 03 14:38:30 -0400 2011
Processing by ArticlesController#index as HTML
Article Load (9.7ms) SELECT `articles`.* FROM `articles`
Rendered articles/index.html.haml within layouts/application (2.7ms)
Rendered user_sessions/_new.html.haml (2.5ms)
Rendered shared/_header.html.haml (3.9ms)
Rendered shared/_footer.html.haml (0.8ms)
Completed 200 OK in 26ms (Views: 9.1ms | ActiveRecord: 9.7ms)
答案 0 :(得分:1)
原来%img{:src => "#"}/
导致页面多次渲染。我删除了这一行,一切正常。如果您需要使用图片占位符,请使用= image_tag ""
,这会导致路由错误,但这比页面呈现多次要好得多。
答案 1 :(得分:0)
如果您使用的是Rails 3+,则应将respond_to :html, :json, :xml
放在控制器的顶部,然后在show
操作中使用respond_with @article
。所以它可能看起来像:
respond_to :html, :json, :xml
def show
article_name = params[:id].gsub('-', ' ')
@article = Article.find_by_name(article_name)
respond_with(@article)
end
它更清洁,更易于维护。
我还建议您查看to_param(http://apidock.com/rails/ActiveRecord/Base/to_param)的文档,而不是您在那里找到的gsub代码,以便按名称而不是ID来查找文章。
如果这没有用,我将不得不在工作之后仔细查看,我可以在测试应用程序中调试一些代码并进行调试。