简体   繁体   English

如何使Rails用新的Javascript文件响应Ajax请求?

[英]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. 我有一个Ajax请求来更新部分网页。 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. 作为此更新的一部分,我想加载一些新的JavaScript,以处理页面的此新加载部分的行为。

The JavaScript that I have directly included in the partial works perfectly: 我直接包含在部分代码中的JavaScript可以正常工作:

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

However, the JavaScript I'm loading with a reference inside the partial is not being loaded: 但是,我正在加载的JavaScript中带有部分内部的引用,但尚未加载:

<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: 我尝试了以下操作,但它似乎可以正常工作,不确定它是否可以在您的情况下正常工作,并且您可能需要重写javascript以获取原型:

<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. 使用jQuery的实时框架应该可以满足您的需求。 Whipped up an example here 这里举个例子

http://jsfiddle.net/bRxxF/ 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. 基本上,您可以使用live来监视页面上与选择器匹配的新dom元素,并响应它们上的事件。 This way your javascript is loaded early but only binds once the ajax happens 这样,您的javascript会提前加载,但仅在ajax发生后才绑定

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

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