Reputation: 111
i have an "ajax engine" based on jQuery. And after receiving the response i must manipulate the response before inserting in page. But I need the response as an jQuery object. I do this with:
tmpActualResult = $( '<span/>' ).html( actualResult );
But at this time jQuery (or browser itself?) execute the scripts which are included in response - and exactly this shouldn't occur. I will execute the scripts manual later.
in particular I will:
in thanks
Edit: If someone is interested too, i've created a more general solution by extending the jQuery.domManip function, as suggested in first answer.
(function($, oldDomManip) {
// Override the core domManip function
$.fn.domManip = function() {
function evalScript(i, elem) {
jQuery.globalEval(elem.text || elem.textContent || elem.innerHTML || "");
}
var scripts = [];
// let jQuery build the fragments
var results = jQuery.buildFragment(arguments[0], this, scripts);
// change parameter to created fragments
arguments[0] = results.fragment.childNodes;
// do what jQuery will do - without scripts
oldDomManip.apply(this, arguments);
if (scripts.length) {
// if connection is active
if (jQuery.active != 0) {
$(this).bind("ajaxStop.scriptCache", function() {
$.each(scripts, evalScript);
$(this).unbind("ajaxStop.scriptCache");
});
} else
$.each(scripts, evalScript);
}
return this;
};
})(jQuery, jQuery.fn.domManip);
it will not execute scripts before ajax request is completed. worked for me.
Upvotes: 4
Views: 4566
Reputation: 2127
Try this:
var container = document.createElement('div');
container.innerHTML = "<div> i am html with script tag <script type="text/javascript">alert('Script executed');</script>end</div>"
$(container).doSomething()
Upvotes: 1
Reputation: 3581
You can't prevent script execution of scripts that are part of a string of markup you're trying to add using .html() or .append(). At least not without extending the domManip function of jQuery. It extracts all scripts in html markup that you're trying to add using .html() or .append() and evals it.
You could, however, extract the script tags with their inner text (js) from the string yourself, add only the markup via .html() or .append() and then eval the scripts yourself when you need to.
Upvotes: 4