Reputation: 43
I need some help with jQuery.
When i'm trying to get html with embded js page content via $.get, it's works good. But when i'm trying to append it to some div, all scripts are removing.
In a console its look fine when i'm doing smthing like this
$('.my_div').html() + '<script>alert("text")</script>'
but when i'm doing
$('.my_div').html($('.my_div').html() + '<script>alert("text")</script>')
script is running and removing
How can i append html+js code to div without running and removing?
Thanks!
UPD:
My example :
index.html
...
<div class="masonry">
<div class="a1">
<p>text</p>
<script>alert('example')</script>
</div>
<div class="a1">
<p>text</p>
<script>alert('example')</script>
</div>
<div class="a1">
<p>text</p>
<script>alert('example')</script>
</div>
</div>
...
<script>
$.get('get_news.php',function(response){
$('.masonry').append(response);
});
</script>
...
get_news.php
<div class="b1">
<p>text</p>
<script>alert('example1')</script>
</div>
<div class="b1">
<p>text</p>
<script>alert('example1')</script>
</div>
<div class="b1">
<p>text</p>
<script>alert('example1')</script>
</div>
...
And i'm going to get
<div class="masonry">
<div class="a1">
<p>text</p>
<script>alert('example')</script>
</div>
<div class="a1">
<p>text</p>
<script>alert('example')</script>
</div>
<div class="a1">
<p>text</p>
<script>alert('example')</script>
</div>
<div class="b1">
<p>text</p>
<script>alert('example1')</script>
</div>
<div class="b1">
<p>text</p>
<script>alert('example1')</script>
</div>
<div class="b1">
<p>text</p>
<script>alert('example1')</script>
</div>
</div>
How can i do it?
Upvotes: 1
Views: 3726
Reputation: 70129
That's the default behavior of .html()
- it will strip out scripts and eval
them while appending content to the DOM. jQuery even provides $.parseHTML
which defaults to stripping out scripts without evaluating them to prevent against XSS.
If you're already executing a script in the page, the vast majority of the time you can just put your code in the same script. But if you really want/need to append a new script to the page, you can do it through append
:
$('.my_div').append($('<script>', { text: 'alert("foo");' }));
Upvotes: 1
Reputation: 3875
You can use append if you don't want to remove the original content. As for stop the script tag from executing, one way is to change to script type to "text/html"
or use html escape function.
Upvotes: 0