[英]How to include a javascript file with Sinatra using ajax
Note: This works fine when I don't use ajax. 注意:当我不使用ajax时,此方法工作正常。 I have the same behavior with slim and haml.
我与苗条和汉默有相同的行为。 Here is the source for using ajax with Sinatra
这是在Sinatra中使用ajax的来源
I am trying to run some javascript in a page created using sinatra while using ajax. 我正在尝试在使用Ajax时使用sinatra创建的页面中运行一些javascript。 See sample using haml below.
请参阅下面的使用haml的示例。 This works fine.
这很好。 Is there any way I can use a file containing javascript, instead of the alert statement below, ie,.
有什么办法可以使用包含javascript的文件,而不是下面的警报声明。 use alert.js
使用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.
当我尝试使用脚本语句时,脚本将嵌入到我的html元素中。 Here is what I am doing:
这是我在做什么:
I am using right.js. 我正在使用right.js。 I add this event handler:
我添加以下事件处理程序:
"#testscript".onClick(function(event) {
event.stop();
$('msg').load("/testscript");
});
and the haml: 和halm:
@@testscript
%p #{@time}
%script src="about.js"
when I do that the p element and the script element are embedded with the div. 当我这样做时,p元素和script元素嵌入div中。
<div id="msg">
<p>The time is 2014-01-05 12:21:39 +0800</p>
<script>
src="about.js"
</script>
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: 为了获得类似的信息,您需要将
src
属性添加为HAML中的属性,如下所示:
%p #{@time}
%script{:src => "about.js"}
The other issue is with your jquery. 另一个问题是您的jquery。 It should be
$('#msg').load
, with the # sign, because that is the id of the div. 它应该是
$('#msg').load
,带有#号,因为那是div的ID。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.