jQuery + Ajax + Haml. js.erb files not firing

允我心安 提交于 2019-11-27 07:15:54

问题


After reading up on a few experiences, I feel this issue might need to be brought up again. Coding in Rails3, I'm trying to implement some smooth Ajax effects when a user tries to create a post on another element of my app. Here's the code I'm concerned with:

app/views/posts/new.html.haml

- form_for @post, :remote=>true do |f|
    = f.text_area :content
    = submit_tag "Post"

app/controllers/post_controller.rb

def create
  @comment = Post.new(params[:post])
  @comment.save
end

app/views/posts/create.js.erb:

alert("ajax worked!");

I've followed what I saw on the UJS Railscast, but nothing seems to be firing. Not only that, but firebug fails to give me any descriptive evidence of what's happening. It tells me that it made the new post object upon submission, but nothing further.

Any ideas?


回答1:


I found the answer! The issue was that when the controller was rendering the view, it was including the overall layout of my application; the layout was yielding to the rendering action, so my javascript code contained inside of my .js.erb file was spit out into my application.rhtml. I fixed this issue by including this inside of my controller action to display my posts:

respond_to do |format|
  format.js {render :layout=>false}
end



回答2:


Watch a Railscast

<%= form_tag products_path, :method => 'get', :id => ↵  
  "products_search" do %>  
  <%= hidden_field_tag :direction, params[:direction] %>  
  <%= hidden_field_tag :sort, params[:sort] %>  
  <p>  
    <%= text_field_tag :search, params[:search] %>  
    <%= submit_tag "Search", :name => nil %>  
  </p>  
<% end %>

and in Js

// Search form.  
  $('#products_search').submit(function () {  
    $.get(this.action, $(this).serialize(), null, 'script');  
    return false;  
  });  
});



回答3:


When my layout was coded in Haml (application.haml), AJAX wouldn't fire and the work-around code kelly.dunn mentioned didn't work.

respond_to do |format|
  format.js {render :layout=>false}
end

The easiest fix was to convert the application layout to .html.erb format.



来源:https://stackoverflow.com/questions/3412375/jquery-ajax-haml-js-erb-files-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!