简体   繁体   中英

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. 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.

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. With my problem, "format.html" will always be first when the page loads. 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?

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.

format.js is only run if rails determines that the request is for JS. Rails defaults to 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 :

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

To send an ajax request for js you thus need to do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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