如何使用Ajax在Sinatra中包含一个javascript文件 [英] How to include a javascript file with Sinatra using ajax
问题描述
注意:当我不使用ajax时,这可以正常工作.我对苗条和咸味有相同的行为.这是源,用于在Sinatra中使用ajax
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
我正在尝试在使用Ajax时使用sinatra创建的页面中运行一些javascript.请参阅下面的使用haml的示例.这很好.有什么办法可以使用包含javascript的文件,而不是下面的警报声明?使用alert.js
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");
以下内容仅是为替代方法提供更多背景知识.当我尝试使用脚本语句时,脚本会嵌入到我的html元素中.这是我在做什么:
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:
我正在使用right.js.我添加了此事件处理程序:
I am using right.js. I add this event handler:
"#testscript".onClick(function(event) {
event.stop();
$('msg').load("/testscript");
});
和haml:
@@testscript
%p #{@time}
%script src="about.js"
当我将p元素和script元素嵌入到div中时.
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>
推荐答案
请注意,您的
<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" />
为了获得类似的结果,您需要将 src
属性添加为HAML中的属性,如下所示:
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"}
另一个问题与您的jquery有关.应该是 $('#msg').load
,带有#符号,因为那是div的ID.
The other issue is with your jquery. It should be $('#msg').load
, with the # sign, because that is the id of the div.
这篇关于如何使用Ajax在Sinatra中包含一个javascript文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!