Rails, jQuery, .js.erb files, JS not executed by the browser

假装没事ソ 提交于 2019-12-09 09:13:50

问题


I'm trying to use jQuery, and everything has been great, until now, when I'm trying to render a partial and append it to a div. Here is how I have it set up:

I have an action that responds to js:

def index
  @objects = Object.find(:all)

  respond_to do |format|
    format.js
  end
end

And a template called index.js.erb with some javascript in it:

alert("hello world");

Firebug returns a "text/javascript" response containing:

alert("hello world");

But the alert window does not appear, nor does any other JavaScript work. I checked out http://railscasts.com/episodes/136-jquery And am more or less following along. I tried several other things, like using .rjs instead of .erb and putting this in my template:

page.alert("hello world"); 

but I get the same exact result, and the browser never executes the JS.

Anyone know why the JavaScript isn't being executed?

I'm running Rails 2.3.4.


回答1:


You have to call it from your view or it will never be executed.

an example controller:

def index
  @objects = Object.find(:all)

  respond_to do |format|
    format.js{
      render :text => "alert('hello')"
    }
  end
end

and an index.html.erb with:

<script type="text/javascript">
  $(function(){
    $.ajax({ url: '/controller', type: 'get', dataType:'script' });
  });
</script>

replace '/controller' with the actual url that executes that controller's index action, by default for PostsController it will be '/posts' and so on...

if you like rjs you delete the {} and everithing in it in the controller and create an index.js.erb or index.rjs with:

page.alert("hello world")

or:

page << "hello world"


来源:https://stackoverflow.com/questions/2016351/rails-jquery-js-erb-files-js-not-executed-by-the-browser

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