使用content_for和ajax / Jquery来部分更新网页

感谢本网站上的人们的大力帮助,我一直在慢慢学习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没有嵌入到我的页面中.我认为这是因为DOM中不再存在content_for js_imports.我可以在我的测试页面添加’content_for’标签,但随后脚本会在我的DIV中添加ID内容.我正在尝试以某种方式将我的脚本添加到我现有脚本下的页面末尾.我知道我可以使用javascript添加和删除脚本,但我想知道是否有办法用标签助手做到这一点?

最佳答案 您无需将这些数据包含在content_for块中.只需直接包含它:

%= 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,显示了你想要的东西.

点赞