问题
I've been slowly learning Mojolicious and Perl thanks to the great help from those on this site. I have been trying to determine the best way to dynamically update parts of my page based on the results of Jquery get calls.
At the moment I have a template like this (Thanks to one of the Mojo contributors Joel)
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
%= content
%= include 'common_js'
%= content_for 'js_imports'
</body>
</html>
Then I have a page that uses this layout, like below.
%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-->
So when the 'testbutton' is clicked I am writing the response from the get request to the div with id content.
The 'data' I'm getting back is;
% 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">
Now, my javascript above isn't embedded in my page. I think its because content_for js_imports no longer exists in the DOM. I can add a 'content_for' tag to my test page, but then the script is added within my DIV with ID content. What I'm trying to achienve somehow is have my script added to the end of the page under my existing script. I know I can use javascript to add and remove script but I was wondering if there is a way to do it with tag helpers?
回答1:
There's no need to include that data your getting back in a content_for block. Just include it directly:
%= 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">
And if you don't want it to replace the existing content, but just append to it, then use append
instead of html
:
$("div#content").append(data);
Joel Berger (in the comments) created a nice pastie that shows what you want.
来源:https://stackoverflow.com/questions/15713470/using-content-for-and-ajax-jquery-to-partially-update-webpage