简体   繁体   中英

How to make Rails respond to Ajax request with a new Javascript file?

I have an Ajax request that comes in to update part of the webpage. This is the code I have doing that:

render :update do |page|
  page.replace_html "my_id", :partial => "my_partial"
end

As part of this update, I would like to load in some new JavaScript, that handles the behavior of this newly loaded part of the page.

The JavaScript that I have directly included in the partial works perfectly:

<script type="text/javascript">
  alert('reached');
</script>

However, the JavaScript I'm loading with a reference inside the partial is not being loaded:

<script type="text/javascript" src="/javascripts/myScript.js"></script>

What's the proper way to be doing this?

I tried the following and it seems to work, not sure if it will work in your situation and you might have to rewrite the javascript for prototype:

<script type="text/javascript">
var e = document.createElement('script')
e.setAttribute("type","text/javascript");
e.setAttribute("src", 'url_of_js_external');
document.getElementsByTagName('head')[0].appendChild(e);
</script>

Using jQuery's live framework should do what you want. Whipped up an example here

http://jsfiddle.net/bRxxF/

$('.doit').live('click',function(){
   $(this).addClass('red');
});

Basically you can use live to watch for new dom elements on the page that match your selector and respond to events on them. This way your javascript is loaded early but only binds once the ajax happens

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