I have an ajax call which returns me following response:
<div class="content">
<script language="JavaScript">
function validate(){
alert('validate is working');
}
</script>
<div class="container">
<a href="#" onclick="javascript:validate();">my button</a>
</div>
</div>
Now, i want to convert the response into html and append it to the page, which made the ajax call.
$.get('test.php', function(data) {
$('#someTarget').append($(data).find('.content').html());
});
I have tried above code, but it seems this only append container div. Is there a way to append javascript code block into my existing page?
In your code are two problems:
$(data)does parse and execute your script, before you inserted it into DOMassuming you meant
$(data).find('.content').html()the html() returns the innerHTML of content, you only need$(data).Try this:
Now there is a trick: I’m using
<style>to wrap scripts, that should be executed after interpreting and inserting into DOM.Okay for your simple validate function that gets called by a click handler, you currently don’t need my trick for inline scripts, however you will need it, when you have active scripts, that should be executed after the HTML is parsed and inserted.
Update: If you don’t want the ‘.content’ to be inserted, don’t use html() – because it returns a string, so you do parse the html twice. Use instead
.append( $(".container", $(data)) )or.append( $(data).find(".container") ).