jquery html() strips out script tags

前端 未结 5 972
再見小時候
再見小時候 2020-11-28 14:17

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

5条回答
  •  时光说笑
    2020-11-28 14:52

    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 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.

提交回复
热议问题