简体   繁体   English

response_to块中的Format.js无法以条件格式运行

[英]Format.js in respond_to block doesn't work in an conditional format

I have this respond_to block which if a param is present, "format.js" will fire or else "format.html" will fire. 我有这个response_to块,如果存在参数,则将触发“ format.js”,否则将触发“ format.html”。 My problem is this, the params will never be present initially, only until a user clicks on a link, which then fires an ajax response. 我的问题是,参数最初不会出现,只有在用户单击链接后才会触发ajax响应。

Here is the block: 这是块:

respond_to do |format|
  if params[:tab_id].present?
    format.js
  else
    format.html
  end
end

I found this post: JQuery posting form via AJAX not triggering rails respond_to format.js which seems to be a fix, but a reason I don't seem to understand why it works. 我找到了这篇文章: 通过AJAX的JQuery发布表单没有触发rails_result_to format.js ,这似乎是一个解决方法,但是我似乎不明白它为什么起作用的原因。 With my problem, "format.html" will always be first when the page loads. 对于我的问题,页面加载时“ format.html”将始终是第一个。 How can I fix this so that "format.js" will fire when the user clicks on a link so that a params will be present? 如何解决此问题,以便在用户单击链接时触发“ format.js”,从而显示参数?

The format of the response is determined by the Accept header and the presence of a format (like .js or .html) on the request path. 响应的格式由Accept标头和请求路径上是否存在格式(如.js或.html)确定。

format.js is only run if rails determines that the request is for JS. 仅当rails确定请求是针对JS时,才运行format.js Rails defaults to format.html . Rails默认为format.html Attempting to use a param for this is just not a good or even doable idea. 尝试为此使用参数不是一个好主意,甚至不是可行的主意。

These are the MIME types Rails recognize as js : 这些是Rails识别为js的MIME类型:

Mime::Type.register "text/javascript", :js, %w( application/javascript application/x-javascript )

To send an ajax request for js you thus need to do: 因此,要向js发送ajax请求,您需要执行以下操作:

var promise = $.ajax('/somepath.js');
// or
var promise = $.ajax('/somepath', {
  dataType: "text/javascript" // or just "script"
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM