How to include a javascript file with Sinatra using ajax

烂漫一生 提交于 2019-12-24 19:28:36

问题


Note: This works fine when I don't use ajax. I have the same behavior with slim and haml. Here is the source for using ajax with Sinatra

I am trying to run some javascript in a page created using sinatra while using ajax. See sample using haml below. This works fine. Is there any way I can use a file containing javascript, instead of the alert statement below, i.e,. use alert.js

@@testjavascript
%p #{@time}
:javascript
  alert("Hello world");

The following is just to give additional background on an alternative approach. When I try to use the script statement, the script gets embedded within my html element. Here is what I am doing:

I am using right.js. I add this event handler:

"#testscript".onClick(function(event) {
  event.stop();
  $('msg').load("/testscript");
});

and the haml:

@@testscript
%p #{@time}
%script src="about.js"

when I do that the p element and the script element are embedded with the div.

<div id="msg">
  <p>The time is 2014-01-05 12:21:39 +0800</p>
  <script>
    src="about.js"
  </script>

回答1:


Notice that your output of

<script>
  src="about.js"
</script>

isn't actually what you likely want. What you really want is probably something more like this:

<script src="about.js" />

In order to get something like that, you need to add the src attribute as an attribute in the HAML, like this:

%p #{@time}
%script{:src => "about.js"}

The other issue is with your jquery. It should be $('#msg').load, with the # sign, because that is the id of the div.



来源:https://stackoverflow.com/questions/20930055/how-to-include-a-javascript-file-with-sinatra-using-ajax

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