Question

I have an AJAX response that contains some HTML, including <script> elements.

This HTML should replace an existing element, but when I use:

$(element).replaceWith($(response))

I lose the script tags from it...

How can I insert the HTML exactly how it is sent?

Was it helpful?

Solution

This code is from facebook's sample app. Insert <div id="fb-root"></div> in your document. The code requires jQuery to load up the script. In your case, replace //connect...../all.js' with the <script> elements.

(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());

OTHER TIPS

It will return a string!!

$.get("ajax.php")
     .success(function(returningHtmlString) {
          $(element).replaceWith(returningHtmlString);
     });

See jQuery.parseHTML( data [, context ] [, keepScripts ] )

The following should work

var content = jQuery.parseHTML(response, document, true)
$(element).replaceWith(content)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top