开发者

jquery html() strips out script tags

I need to replace the content of a div in my page with the html resultant from an ajax call. The pro开发者_如何转开发blem 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.


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.


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!


This is the easiest solution:

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

This will keep the script tags in ;)


Try

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

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


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');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜