感谢这个网站上的人的大力帮助,我一直在慢慢学习 Mojolicious 和 Perl。我一直在尝试根据 Jquery get 调用的结果确定动态更新页面部分的最佳方法。
目前我有一个像这样的模板(感谢 Mojo 贡献者之一 Joel)
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
%= content
%= include 'common_js'
%= content_for 'js_imports'
</body>
</html>
然后我有一个使用此布局的页面,如下所示。
%title 'Script Test';
% content_for 'js_imports' => begin
%= javascript begin
$(document).ready(function(){
$("input#testbutton").click(function(){
$.get('<%= url_for('testbutton') %>',
function (data) {
$("div#content").html(data);
});
})
});
% end
% end
<p>Main Page</p>
<input type="button" id="testbutton" class="btn btn-danger" value="test">
<div class="span9" id="content"></div><!--/span9-->
因此,当单击“testbutton”时,我会将 get 请求的响应写入具有 id 内容的 div。
我返回的“数据”是;
% content_for 'js_imports' => begin
%= javascript begin
$(document).ready(function(){
$("input#testbutton2").click(function(){
alert('testbutton2 clicked');
});
});
% end
% end
<p>Test Button Clicked</p>
<input type="button" id="testbutton2" class="btn btn-danger" value="test2">
现在,我上面的 javascript 没有嵌入到我的页面中。我认为这是因为 content_for js_imports 不再存在于 DOM 中。我可以将“content_for”标签添加到我的测试页面,但随后脚本会添加到我的 DIV 中并包含 ID 内容。我试图以某种方式实现的是将我的脚本添加到现有脚本下的页面末尾。我知道我可以使用 javascript 添加和删除脚本,但我想知道是否有办法使用标签助手来做到这一点?
最佳答案
无需将您获取的数据包含在 content_for block 中。直接包含它即可:
%= javascript begin
$(document).ready(function(){
$("input#testbutton2").click(function(){
alert('testbutton2 clicked');
});
});
% end
<p>Test Button Clicked</p>
<input type="button" id="testbutton2" class="btn btn-danger" value="test2">
如果您不希望它替换现有内容,而只是追加到其中,则使用 append
而不是 html
:
$("div#content").append(data);
Joel Berger(在评论中)创建了一个不错的 pastie这显示了您想要的内容。
关于jquery - 使用 content_for 和 ajax/Jquery 部分更新网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15713470/