29

I need to replace the content of a div in my page with the html resultant from an ajax call. The problem is that the html have some necessary scripts in it and it seems that jquery html() function stripts them out, I need to filter the response and only get a specific div.

I am thinking on a workaround which is to extract all the script tags from the ajax response and then append them do the DOM but i am having trouble doing that.

Here is my code;

   $('a.link-vote').live('click',function(){
        var idfeedback = $(this).attr('id').split('-')[1];
        var href = $(this).attr('href');
        $('.feedback-' + idfeedback + '-loader').show();
        $.ajax({
            type: "POST",
            url: href,
            success: function(response){
               var x = $(response).find('#feedback-'+ idfeedback).html();
               $('.feedback-' + idfeedback + '-loader').hide();
               $('#feedback-'+ idfeedback).html(x);

            }
        });
        return false;
    });

I found this old topic: jQuery - script tags in the HTML are parsed out by jQuery and not executed

but the is any conclusion. I tried the solutions suggested there but none of them work.

EDIT: I seem to found a workaround based on that old topic but it´s not pretty;

  var dom = $(response);
                // var x = $(response).find('#feedback-'+ idfeedback).html();
                $('.feedback-' + idfeedback + '-loader').hide();
                //$('#feedback-'+ idfeedback).html(x);

                $('#feedback-'+ idfeedback).html(dom.find('#feedback-'+ idfeedback).html());

                dom.filter('script').each(function(){
                    var obj = $(this);
                    $('#feedback-'+ idfeedback + ' .feedback-comments').append(obj);
                });

There must be a easy way.

5 Answers 5

28

Edit: I'm tired and not thinking. You can just use the native innerHTML method instead of .html():

$('#feedback-' + idfeedback)[0].innerHTML = x;

Original answer:

My hunch is that the answer you linked doesn't work for you because the included scripts are called with a src attribute rather than script content between the <script> and </script> tags. This might work:

$.ajax({
    url: 'example.html',
    type: 'GET',
    success: function(data) {

        var dom = $(data);

        dom.filter('script').each(function(){
            if(this.src) {
                var script = document.createElement('script'), i, attrName, attrValue, attrs = this.attributes;
                for(i = 0; i < attrs.length; i++) {
                    attrName = attrs[i].name;
                    attrValue = attrs[i].value;
                    script[attrName] = attrValue;
                }
                document.body.appendChild(script);
            } else {
                $.globalEval(this.text || this.textContent || this.innerHTML || '');
            }
        });

        $('#mydiv').html(dom.find('#something').html());

    }
});

Note, this has not been tested for anything and may eat babies.

3
  • 1
    .innerHTML working ok but script inside new content don't get execute... any idea ?
    – AGupta
    Jan 14, 2014 at 14:33
  • @Aman, please post a question with an explanation of what you are trying to do, what you've tried, and how it is failing. Jan 15, 2014 at 3:59
  • Any ideas why the script tags are being extracted?
    – JDandChips
    Oct 30, 2015 at 17:05
4

I had the same problem, but with more issues which I couldn't fix that easily. But I found a solution:

This is my pseudo-source (HTML) that I couldn't change in any way.

<html>
  <body>
    <div id="identifier1">
      <script>foo(123)</script>
    </div>
    <div id="identifier2">
      <script>bar(456)</script>
    </div>
  </body>
</html>

I used $.get() to fetch this HTML page. Now that I have the code as a string, it's time to search in it with jQuery. My aim was, to isolate the Javascript-Code inside the <script>-Tag, that belongs to the DIV identifier2, but not to identifier1. So what I wanted to get is bar(456) as a result string. Due to the reason, that jQuery strips all script-Tags, you cannot search like this anymore:

var dom = $(data); //data is the $.get() - Response as a string
var js = dom.filter('div#identifier2 script').html();

The solution is a simple workaround. In the beginning we will replace all <script>-Tags with something like <sometag>:

var code = data.replace(/(<script)(.*?)(<\/script>)/gi, '<sometag$2</sometag>');
var dom = $(code);
var result = dom.find('div#identifier2 sometag').html(); 

//result = bar(456)

It's a simple hack, but it works!

1
  • 2
    I despise this hack but it works so I voted it up. HTML sometimes forces you to do such things.
    – usr
    Feb 6, 2013 at 19:03
4

This is the easiest solution:

var keepScripts;
keepScripts = true;
$.parseHTML(yourHtmlString, keepScripts);

This will keep the script tags in ;)

-3

Try

$('#feedback-'+ idfeedback).empty().append(response);

I didn't tested. Not sure if .html() really strips <script> but give this a try.

1
  • 1
    iT works that way but i need to filter the response before adding to the DOM. I tried this var x = $(response).find('#feedback-'+ idfeedback); $('#feedback-'+ idfeedback).empty().append(x); but then the scripts are stripped again
    – brpaz
    Nov 2, 2010 at 16:18
-9

Can you show me the result html structure ?

UPDATE 2010/11/03

You can eliminate <script> tag from .html() result with regular expression.
From your first code, after this line.

var x = $(response).find('#feedback-'+ idfeedback).html();

You can do something like this.

x = x.replace(/\n/g, '{n}')
.replace(/<script.*?<\/script>/g, '')
.replace(/{n}/g, '\n');
2
  • the response appears correctly with all the scripts. but any filter i apply after that in strips the script tags.
    – brpaz
    Nov 2, 2010 at 16:19
  • 5
    It's not even what he was asking. He's asking completely the opposite.
    – InspiredBy
    Jul 25, 2012 at 17:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.